PHP Cookie and Session Application Learning Note _php Tutorial

Source: Internet
Author: User
Tags setcookie
In PHP, the difference between a cookie and a session is that the cookie data is stored on the client, the session data is stored on the server side, and naturally there are some details on how to use it, but the latter is much safer.

1.cookie&session Introduction and differences

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

Simply put, when you log on to a website, if the Web server side uses the session, then all the data is stored on the server, the client each time the server is requested to send the current session of the SessionID, The server determines the appropriate user data flag based on the current SessionID to determine whether the user is logged on, or has some kind of permission. Since the data is stored on the server, you can't forge it, but if you can get the SessionID of a logged-on user, it can be successful to forge the user's request with a special browser. SessionID is a server and client link when randomly assigned, generally there will be no duplication, but if there is a large number of concurrent requests, there is no possibility of duplication, I have encountered once. Login to a website, start to display their own information, and so on for a period of time expired, a refresh, actually show someone else's information.

If the browser is using a cookie, then all the data is stored on the browser side, such as when you log in, the server set the cookie User name (username), then, when you request the server again, the browser will username a piece sent to the server, These variables have certain special markings. The server is interpreted as a cookie variable. So as long as you do not close the browser, then the cookie variable is always valid, so it can be guaranteed for a long time not to 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're legit. Therefore, the use of cookies is more likely to be attacked. If it is set to a valid time, then it will save the cookie on the client's hard disk, the next time you visit the website, the browser first check whether there is a cookie, if any, read the cookie, and then sent 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, then he or she logs in as your identity. So a cookie can be forged. Of course, the forgery of the need for ideas, directly copy the cookie file to the cookie directory, the browser is not recognized, he has a index.dat file, stored the cookie file set up time, and whether there is modification, so you must first have to have the site of the cookie file, and to ensure that the time to deceive the browser, once in the school's VBB forum has done experiments, copy other people's Cookie login, take the name of others to post, no problem at all.

Session is a server-side storage space maintained by the application server, when the user connects to the server, a unique SessionID is generated by the server, which uses the SessionID as an identifier to access the server-side session storage space. And SessionID this data is saved to the client, saved with a cookie, when the user submits the page, the SessionID will be submitted to the server side, to access the session data. This process is not a developer intervention. So once the client disables cookies, the session will also expire.

The server can also pass the SessionID value 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 rewriting the URL, and the process is transparent to the programmer.

You can try it, even if you do not write cookies, use Request.getcookies (), the length of the cookie array is also 1, and the name of this cookie is jsessionid, and there is a long binary string, Is the value of the SessionID.

Configuration and application of 2.cookie

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

Access and process 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
To delete the basic syntax:

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


The code is as follows Copy Code

if ($_post[' user '] && $_post[' password ']) {
Setcookie ("Us", $_post[' user ');
Setcookie ("pwd", $_post[' password ');
echo "User:". $_cookie[' Us ']. "
"." Password: ". $_cookie[' pwd '];

Note: Cookies must be done before the output, otherwise error.


Configuration and application of 1.session

Basic syntax:

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

Examples to illustrate the difference between a session and a cookie

<一> : Session

Start session:

Session_Start ();

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

Set session:

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

PS: When using, directly use the $_session[] method to set the value, where the "[]" section is the name of the SESSION, "=" followed by a value.

Read session:

echo $_session[' name '];

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

Destroy session:

1. Close the browser and destroy it automatically.

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

<二> : Cookies

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: The time at which the validity period ends,

Path: Valid directory,

Domain: Valid domain name, top-level domain unique

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

For example:

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

Setcookie ("username", ' hello ', Time () +3600, "/~rasmus/", ".", 1);

Output data operation cannot occur before Ps:setcookie, otherwise an error similar to Session_Start () will occur.

Read cookies:

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

echo $HTTP _cookie_vars["username"];

PS: Two kinds of output mode.

Destroying cookies:

Set a past time to unregister cookies

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

Output data operation cannot occur before Ps:setcookie, otherwise an error similar to Session_Start () will occur.



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


1.SESSION stored on the server side, users can not be modified, more secure, cookies stored on 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. The cookie is stored in the TEMP directory under user Windows.

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

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

5. The session cannot be used after a cookie has been disabled

6.session use the time to add session_start () and cannot have any output in front. true techarticle in PHP, the difference between a cookie and a session is that the cookie data is stored on the client, the session data is stored on the server side, and naturally there will be some details on the way to use it, but later than the previous ...

  • Related Article

    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: 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.