(Advanced article) on the relationship and difference between Cookie and session

Source: Internet
Author: User
Tags set cookie

Cookie Introduction

Cookies are often used to identify users. A cookie is a small file that the server leaves on the user's computer. Whenever the same computer requests a page through a browser, it also sends a cookie. With PHP, you can create and retrieve the value of a cookie.

1. Set Cookies

PHP uses the Setcookie function to set cookies.

The Setcookie function defines a cookie and attaches it behind the HTTP header, and the Setcookie function is prototyped as follows:

int Setcookie (string name, string value, int expire, string path, string domain, int secure);

Parameter description: Cookie name, cookie value, expiration time (int), valid path, limited domain name, HTTPS delivery is valid

Note: The cookie that is currently set does not take effect immediately, but is not visible until the next page. This is due to the fact that the cookie is passed to the client's browser on this page and the next page browser will be able to remove the cookie from the client's machine and return it to the server.

Examples of Use:

Normal use:

Setcookie (' name ', ' PHP ');

With time of failure:

Setcookie (' name ', ' PHP ', Time () +24*60*60);//1day

Cookies are path-oriented and are stored by default under the current file, and if no path is set, cookies under different files are saved in different folders by default and saved under the MyTest folder by default

2. Receiving and processing cookies

The web communication protocol between the client and the server is HTTP. The three ways PHP uses HTTP to get user data are: Post method, get method and cookie. The PHP default delivery method is a cookie and is the best method.

For example, setting up a cookie,php named Mycookier will automatically parse it from the HTTP header received by the Web server and form a variable like the normal variable named $mycookie, which is the value of the cookie.

3. Delete Cookies

There are two ways to delete an already existing cookie:

One is to call the Setcookie with the name parameter only, then the cookie named this name will be deleted from the connections machine, for example: Setcookie (' name ', ' ");

Another option is to set the cookie to expire at time () or 1, and then the cookie is deleted after the page has been browsed (it is actually invalid). For example: Setcookie (' name ', ' php Huaibei ', Time () -24*60*60);

Note that when a cookie is deleted, its value is still valid on the current page.

Precautions for using cookies:

First, it must be set before the content output of the HTML file (the cookie is part of the HTTP protocol header for passing information between the browser and the server, so the cookie function must be called before any content output that belongs to the HTML file itself.)

The PHP page can be used first

Ob_start ();//Open

Code .....

Ob_end_flush (); Refresh Cache

Can prevent the header prompt error);

Different browsers do not have the same mechanism for cookie processing

The cookie limit is on the client side. A browser can create a maximum of 30 cookies, and each cannot exceed 4KB, and each Web site can set a total of no more than 20 cookies.

The currently set cookie does not take effect immediately, but will not be visible until the next page

Session Introduction

Session mechanism is a server-side mechanism, the server uses a hash-like structure (or perhaps a hash table) to save information, each site visitor will be assigned to a unique identifier, the session ID, it is stored in two forms: either through the URL is passed, It is stored in the client's cookie. Of course, you can also save the session to the database, which will be more secure, but the efficiency will be reduced. URL delivery security must be too bad, PHP's session mechanism is to set the cookie, save the session ID in the cookie ( Session ID), a session file is generated on the server side, associated with the user, and the Web application stores the data associated with these sessions and passes between pages.

PHP related functions

There are a lot of functions in PHP about sessions, but the ones we use the most are the following:

Session_Start (): Enables the session mechanism to call it at the very beginning of the program file that needs to be used for the session.

Session_register (): Register Session variable

Session_unregister (): Delete Session variable (one delete)

Session_is_registered (): Determine if the session variable is registered

Session_distroy (): Destroys all session variables (all session variables are destroyed, including files)

There are a few things to keep in mind:

1. function session_start () must be executed at the very beginning of the program and cannot have any output in front of it, otherwise

It will appear "Warning:cannot send session Cookie-headers already

Sent "a warning message similar to this.

2. The function Session_register () is used to register related variables to be saved in the session, using the following:

<?php

$val = "Session value";

Session_register ("Val");

?>

Val is the name of the session variable to be registered, do not add the "$" symbol when registering, just write its variable name.

3. Function Session_unregister () is exactly the same as the above function, but functionally opposite, the above function is registered

Session variable, which is the deletion of the specified session variable.

4. Function session_is_registered () is used to determine if the session variable is registered.

5. Function Session_destroy () is mainly used to destroy all session variables when the system logs off and exits, it has no parameters and can be called directly.

The relationship between session and PHP.ini configuration

1,session.save_handler = File

The way to read/write back session data, by default, files. It allows the session management function of PHP to store session data using the specified text file

2,session.save_path = "/xammp/temp/"

Specifies the directory where the session file is saved, can be specified to another directory, but the specified directory must have the httpd daemon owner (such as Apache or WWW, etc.) write permission, or cannot save the session data. It can also be written like this session.save_path = "N;/path" where N is an integer. This allows not all session files to be stored in the same directory, but scattered in different directories. This is useful for servers that handle a large number of session files. (Note: Directories need to be created manually)

3,session.auto_start = 0

If this option is enabled, the session will be initialized for each request of the user. Deprecated, it is best to initialize the session with the Session_Start () display.

: The left side is the session file saved under xammp/tmp/, which is the format of PHP serialization

Right: The first line is echo serialize ($_session[' name ");//serialization

The second line is to print the session value

Where the file name is Session-name and the content is in PHP serialized format

The difference and relationship between a cookie and a session

Storage location:

Session is stored in the server location, you can configure the session configuration via PHP.ini

Cookies are stored on the client side (in fact, there are two kinds of:

1, persistent cookie, set the time of the cookie to be present on the hard disk as a file,

2, session cookie, not set cookie time, Cookie life cycle is closed before the browser disappears, usually not saved on the hard disk, but stored in memory)

The relationship between a cookie and a session

From the figure above you can see:

The cookie is sent via the HTTP header:

Cookie name=php%bb%b4%b1%b1; Phpsessid=cpt2ah3pi4cu7lo69nfbfllbo7

PHPSESSID is the important parameter of the association server session.

Look again session file: Sess_cpt2ah3pi4cu7lo69nfbfllbo7

The session_id generation format is: Sess_ plus a string of PHPSESSID values

We can understand this:

When a program needs to create a session for a client's request, the server first checks to see if the client's request contains a session ID (called the session ID.), and if it is included, it has previously created a session for this client. The server will follow the session ID to retrieve the session (not retrieved, a new one), if the client request does not include session ID, then create a session for this client and generate a session ID associated with this session, The value of session ID should be a string that is neither duplicated nor easy to be found, and the session ID will be returned to the client in this response to save. This session ID can be saved by using a cookie so that the browser can automatically send the tag to the server in the interactive process. Generally the name of this cookie is similar to Seeesionid

PHP.ini inside about session and cookie-related configuration

1,session.use_cookie = 1

Whether to pass the session ID value using the cookie method. The default is 1, which means enable.

2,session.name = Phpsessid

Regardless of whether the cookie is passed sessioin_id or the Get method passes the session_id, the key value needs to be used. Their format is cookie:sess_name=session_id, and/path.php?sess_name=session_id, of which sess_name is specified here.

3,session.use_only_cookies = 0

Indicates that the session ID is passed only using the cookie method. We have said that the method of passing cookies, in addition to cookies and get methods, is an unsafe method. When cookies are disabled on the client side, the Get method is used to pass the session_id, which can be used to pass session_id with the Get method.

4,session.cookie_lifetime = 0, Session.cookie_path =/And Session.cookie_domain =

If you use the cookie method to pass session_id, the cookie valid domain, directory, and time are specified here respectively. corresponding to the parameter $expire, $path and $domain of the Setcookie () function respectively. Where cookie_lifetime=0 indicates that cookies are not deleted until the browser is closed. You can also use the Session_set_cookie_params () function to modify these values.

5,session_name ([string $name])

Gets or updates the session_name. If name is passed, it means that the default name Phpsessid (by Session.name) is not used, otherwise the current session_name is obtained. Note: If you set Session_name, you must call before Session_Start () to take effect.

6,SESSION_ID ([string $id])

Similar to Session_name (), but it is a way to read or set session_id. Similarly, if session_id is set, it must be called before session_start () is valid.

7,session_set_cookie_params () and Session_get_cookie_params ()

With Session_set_cookie_params () You can reset Session.cookie_lifetime, Session.cookie_path and Session.cookie_ Domain of the three php.ini settings. The Session_get_cookie_params () is the value that gets these settings.

Summarize:

The client-side cookie security of the server session is a bit higher

The session is prone to being out of sync when the server is clustered, and cookies do not

(Advanced article) on the relationship and difference between Cookie and session

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.