Cookies in PHP and session application learning notes

Source: Internet
Author: User
Tags php and sessions setcookie

1.cookie&session Introduction and differences

The cookie data is saved on the client and the session data is saved on the server side.

Simply put, when you log on to a Web site, if the Web server side is using session, then all the data is stored on the server, the client each time the server will send the current conversation SessionID, The server judges the appropriate user data flags based on the current SessionID to determine whether the user is logged on or has some sort of permission. Since the data is stored on the server, you cannot forge it, but if you can get a sessionid of a logged-on user, it can be successful to falsify the user's request with a special browser. SessionID is the server and client links randomly allocated, generally there will be no duplication, but if there is a large number of concurrent requests, nor is there no possibility of duplication, I have encountered once. Login to a website, starting to show their own information, and so on a period of time timed out, a refresh, incredibly show someone else's information.

If the browser is using cookies, then all the data is stored on the browser side, for example, after you log in, the server has a cookie username (username), then when you request the server again, the browser will send username piece to the server, These variables have certain special tags. The server is interpreted as a cookie variable. So as long as you do not close the browser, the cookie variable is always valid, so you can guarantee a long time does not drop the line. If you can intercept a user's cookie variable and then forge a packet to send the past, the server still thinks you are legal. Therefore, using cookies is more likely to be attacked. If you set a valid time, it will save the cookie on the client's hard disk, and the next time you visit the Web site, the browser first checks for cookies and, if so, reads the cookie and sends it to the server. If you save a forum cookie on a machine that is valid for one year, if someone invades your machine, copies your cookie, and places it under the directory of his browser, he logs on to the site with your identity. So cookies can be forged. Of course, it takes an idea to fake it, a direct copy of the cookie file to the cookie directory, the browser is not recognized, he has a Index.dat file, store the cookie file creation time, and whether there are changes, so you must first have the site's cookie file, and to ensure that the time to cheat from the browser, once in the school VBB Forum has done experiments, copy other people's Cookies login, risking the name of others posted, there is no problem at all.

Session is a server-side storage space maintained by the application server, and when users connect to the server, a unique SessionID is generated by the server, using the SessionID as an identifier to access the server-side session storage space. And SessionID this data is saved to the client, saved with cookies, when the user submits the page, the SessionID is submitted to the server side to access the session data. This is a process that is not interfered with by developers. So once the client disables cookies, the session is invalidated.

The server can also pass SessionID values through URL rewriting, so it is not entirely dependent on cookies. If the client cookie is disabled, the server can automatically save the session value by overriding the URL, and the process is transparent to the programmer.

You can try it, even if you don't write cookies, use Request.getcookies (), and the length of the cookie array is 1, and the cookie's name is Jsessionid, and there's a very long binary string, Is the value of the SessionID.


configuration and application of 2.cookie

Basic syntax: Setcookie ("Cookie", "Cookievalue", Time () +3600, "/forum", ". xxx.com", 1);
Name value valid time, millisecond path save domain using HTTPS

Accessing and processing cookies
Access Basic Syntax:

The code is as follows Copy Code
Echo $mycookie;
echo $cookiearray [' 0 '];
echo $_cookie[' MyCookie ']; Recommended
echo $HTTP _cookie_vars[' MyCookie '];

Delete Cookies
Delete Basic syntax:

The code is as follows Copy Code
Setcookie ("Cookie", ""); (Overwrite the original value with a blank cookie)
Setcookie ("Cookie", "value", Time () -1/time ()); (Time destroyed)

Instance:

  code is as follows copy code

<?php
if ($_post[' user '] && $_post[' password ']) {
 setcookie ("Us", $_post[' user ');
  Setcookie ("pwd", $_post[' password '));
 echo "User:". $_cookie[' Us ']. " <br/> "." Password: ". $_cookie[' pwd '];
}

<form id= "Form1" Name= "Form1" method= "Post" action= "file.php"
   user:< Input type= "text" name= "user"/>
   <br/>
   Password: <input type= "Text Name=" Password/>
   <input type= "Submit" name= "submit" value= "submit"/>
</form>


Note: You must complete the cookie before the output, otherwise error.

--------------------------------------------------------

Configuration and application of 1.session

Basic syntax:

The code is as follows Copy Code
Session_Start (); Initialization must be placed on the header of the file.
$_session[' name ' = value; Configure session.
echo $_session[' name ']; Use session.
Isset ($_session[' name ')); Judge.
unset ($_session[' name ')); Delete.
Session_destroy (); Destroys all sessions.

Give some examples to introduce the difference between session and Cookie

< a >:session


Start session:


Session_Start ();


PS: This function needs to be placed on the front end of the file, do not have any output before, preferably the head write (do not have leading spaces).


Set session:


$_session[' name ']= ' value ';


PS: When used, set the value directly using the $_session[] method, where the [] section is the name of the session, followed by the value.


Read session:


echo $_session[' name '];

PS: The session (using Session_Start ()) should be opened regardless of whether the session is set or read.

Destroy session:


1. Close the browser and destroy automatically.


2. Direct to $_session[]= '; Empty.

< two >:cookie


To set Cookies:


BOOL Setcookie (string name[,string value[,int expire[,string path[,string domain[,bool secure[,bool HttpOnly]]]

Name:cookie variable Name

The value of the Value:cookie variable

Expire: At the end of the validity period,

Path: Valid directory,

Domain: Valid domain name, top-level domain unique

Secure: If the value is 1, the cookie can only be valid on the HTTPS connection, and HTTP and HTTPS are available if the default is 0.

For example:

Setcookie (' username ', ' hello ', Time () +3600);

Setcookie ("username", "Hello", Time () +3600, "/~rasmus/", ". paea.cn", 1);

The output data operation cannot occur before the Ps:setcookie, or the error will appear similar to Session_Start ().

Read cookies:

echo $_cookie[' username ']. ' | | ';

echo $HTTP _cookie_vars["username"];

PS: Two modes of output.

To destroy Cookies:


Set a past time to unregister cookies

Setcookie (' username ', ' hello ', Time ()-3600);

The output data operation cannot occur before the Ps:setcookie, or the error will appear similar to Session_Start ().

To sum up

Role:

Sessions and cookies are all ways to temporarily record user data.

Difference:

1.SESSION stored on the server side, the user can not modify, more secure, cookies stored in the client, the user may be modified, unsafe.

2.Session will be saved on the server for a certain amount of time and will consume server resources. Cookies are stored in the TEMP directory under user Windows.

3. The limit of a single cookie on the client is 4k

4.session traversal using $_session[], COOKIE traversal using $_cookie[]

5. Session cannot be used after cookies have been disabled

6.session is used with session_start () and no output before.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.