Compare and analyze the similarities and differences of cookie and session in PHP _php skill

Source: Internet
Author: User
Tags hash session id sessions

Let everyone have a more in-depth understanding of cookies and session, and the flexibility of their development work to bring inspiration.

First, the cookie mechanism

Cookies are small pieces of text stored on the local machine by the server and sent to the same server with each request. The IETF RFC 2965 HTTP State Management mechanism is a generic cookie specification. The Web server sends cookies to the client using HTTP headers, and at the client terminal, the browser resolves the cookies and saves them as a local file, which automatically binds any requests to the same server to the cookies.

Specifically, the cookie mechanism uses a scheme that maintains state on the client. It is the memory mechanism of the session state at the client side, and he needs the user to open the cookie support for the clients. The role of cookies is to solve the HTTP protocol stateless defects made efforts.
Orthodox cookie distribution is implemented by extending the HTTP protocol, and the server prompts the browser to generate the appropriate cookie by adding a special line of instructions to the HTTP response header. However, pure client script such as JavaScript can also generate cookies. And the use of cookies by the browser in accordance with certain principles in the background automatically sent to the server. The browser checks all stored cookies and sends the cookie to the server on the HTTP request header of the requesting resource if the cookie is declared to be more than equal to the location of the resource being requested.

The contents of the cookie mainly include: name, value, expiration time, path and domain . A path, together with a domain, forms the scope of the cookie. If you do not set an expiration time, the lifetime of this cookie is the period of the browser session, the cookie disappears when the browser window is closed. This lifetime is known as a session cookie for a browser session-time cookie. Session cookies are generally not stored on the hard disk but are kept in memory, although this behavior is not regulated by the specification. If the expiration time is set, the browser saves the cookie to the hard disk, closes it and opens the browser again, and the cookies are still valid until the expiration date is exceeded. Cookies stored on your hard disk can be shared between different browser processes, such as two IE windows. For cookies stored in memory, different browsers have different ways of handling them.

The session mechanism is a solution that maintains state on the server side. At the same time, we also see that the session mechanism may need to use the cookie mechanism to save the identity because the server-side retention scheme also needs to be stored in the client. The session provides a convenient way to manage global variables.

The session is for each user, the value of the variable is saved on the server, with a sessionid to distinguish which user sessions variable, which is returned to the server through the user's browser, when the client disables cookies, This value may also be set to be returned to the server by get.

In terms of security: When you visit a site using session and create a cookie on your own machine, it is recommended that the session mechanism on the server side be more secure, because it will not read the information stored by the client arbitrarily.

Second, the session mechanism

The session mechanism is a server-side mechanism in which the server uses a structure similar to a hash table (or perhaps a hash table) to hold the information.

When a program needs to create a session for a client's request, the server first checks to see if the client's request already contains a session ID (called a session ID.), or if it has already been previously created for this client, The server retrieves this session using the sessions ID (not retrieved, creates a new one), creates a session for this client, and generates an event ID that is associated with the session if the client request does not contain a session ID. The value of the session ID should be a string that is not duplicated and is not easy to be found, and will be returned to the client for saving in this response.

This session ID can be saved in the form of a cookie, so that the browser can automatically play the logo to the server as per the rules during the interaction. Generally this cookie's name is similar to Seeesionid. However, cookies can be artificially prohibited, and there must be other mechanisms to pass the session ID back to the server when the cookie is blocked.
One technique that is often used is called URL rewriting, which is to attach the session ID directly behind the URL path. There is also a technique called form hidden fields. The server will automatically modify the form and add a hidden field so that the session ID can be passed back to the server when the form is submitted.

Cookies and sessions are capable of session tracking, but the principle of completion is different. Under normal conditions both can satisfy the demand, but sometimes can not use cookies, sometimes can not use session.

The following are compared to illustrate the characteristics of the two and the place to apply.

1. Different ways of accessing

Only ASCII strings can be stored in cookies, and requirements are encoded first if required to access Unicode characters or binary data. Java objects are not directly accessible in cookies. It's hard to use cookies to store slightly more complex information.
The session can access any type of data, including, but not limited to, string, Integer, List, map, and so on. The session can also be directly in the custody of Java beans and even any Java classes, objects, etc., is very convenient to use. The session can be viewed as a Java container class.

2. Differences in privacy policies

Cookies are stored in the client reader and are visible to the client, and some of the client's programs may pry, copy, and modify the contents of the cookie. And the session is stored on the server, the client is transparent, there is no risk of sensitive information leakage.
If you choose cookies, the better way is, sensitive information such as account password and so try not to write to the cookie. It is best to encrypt cookies information like Google and Baidu, submit to the server and then decrypt, to ensure that the information in the cookie as long as I can read. And if the choice of session on the more convenient, anyway, on the server, any privacy can be effectively protected.

3. The difference in the validity period

People who have used Google know that if they log on to Google, Google's login information is valid for a long time. The user does not have to log on every visit, and Google will record the user's login information persistently. In order to achieve this effect, using cookies would be a better choice. You only need to set the expiration time property of the cookie to a large and large number.

Since the session relies on a cookie named Jsessionid, and the cookie Jsessionid expires with –1, simply close the reader and the session will be invalidated, so that sessions cannot complete the effect of the information for an eternity. Use of URL address rewriting can not be completed. And if set the session timeout time is too long, the server cumulative session will be more, the more easily incur memory overflow.

4. Different pressure on the server

Session is kept on the server side, each user will produce a session. If concurrent access to a very large number of users, will produce a lot of session, consuming a lot of memory. Thus, like Google, Baidu, Sina, such as the high number of concurrent access to the site, is unlikely to use the session to track customer conversations.

Cookies are kept on the client and do not occupy server resources. Cookies are a good choice if you read a lot of concurrent users. Cookies may be the only option for Google, Baidu, and Sina.

5. browser support for different

Cookies need to be supported by the client browser. If the client disables cookies or does not support cookies, session tracking is invalidated. For WAP applications, regular cookies are useless.

If the client browser does not support cookies, you need to use session and URL rewrite. All you need to be aware of is that the URL of the session program should be overridden by the URL address, or it will fail. For WAP applications, Session+url address rewriting may be its only option.

If the client supports cookies, the cookie can be set to both the browser window and the child window (the expiration Time is –1), and it can be set to be valid in all reader windows (set the expiration time to an integer greater than 0). However, the session can only be valid within the Reader window and its child windows. If two browser windows are irrelevant, they will use two different sessions. (IE8 under different window session coherence)

6. Cross-domain support differences

Cookies support Cross-domain access, for example, if the domain property is set to ".", all domain names with the suffix "." can access the cookie. Cross-domain cookies are now widely used in networks, such as Google, Baidu, Sina, and so on. The session does not support cross domain access. The session is valid only in the domain in which he is located.
Using cookies alone or using session only may not accomplish the desired results. Then you should try using cookies and sessions at the same time. The combination of cookie and session will accomplish a lot of unexpected results in a practical project.

The above is for PHP in the cookie and session of the distinction between comparison, I hope to help you learn.

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.