Comparison and analysis of similarities and differences between cookies and sessions in php

Source: Internet
Author: User
Tags send cookies
This article mainly compares and analyzes the differences between cookies and sessions in php in multiple aspects, and briefly introduces and summarizes cookies and sessions, if you are interested, you can refer to this article to gain a deeper understanding of cookies and sessions, and provide inspiration for the flexible use of cookies and sessions in your development work.

I. cookie mechanism

Cookies are small pieces of text stored by the server on the local machine and are sent to the same server as each request. Ietf rfc 2965 HTTP State Management Mechanism is a common cookie specification. The network server uses the HTTP header to send cookies to the client. on the client terminal, the browser parses these cookies and saves them as a local file. then, it automatically uploads these cookies to any requests on the same server.

Specifically, the cookie mechanism adopts the client-side persistence scheme. It is the storage mechanism of session status on the user end. it requires the cookie support from the user to open the client. Cookie is used to solve the stateless defects of HTTP.
The Orthodox cookie distribution is implemented by extending the HTTP protocol. the server prompts the browser to generate the corresponding cookie by adding a special line in the HTTP response header. However, pure client scripts such as JavaScript can also generate cookies. Cookies are automatically sent to the server in the background by the browser according to certain principles. The browser checks all stored cookies. if the declared range of a cookie is greater than or equal to the location where the requested resource is located, the cookie is attached to the HTTP request header of the requested resource and sent to the server.

Cookie content mainly includes:Name, value, Expiration Time, pathAndDomain. The path and the domain form the scope of the cookie. If no expiration time is set, it indicates that the cookie's life cycle is the browser session period. when the browser window is closed, the cookie disappears. This cookie is called a session cookie. Session cookies are generally stored in the memory instead of on the hard disk. of course, this behavior is not standardized. If the Expiration Time is set, the browser will save the cookie to the hard disk, close it, and open the browser again. These cookies are still valid until the preset expiration time is exceeded. Cookies stored on hard disks can be shared among different browser processes, such as two IE windows. For cookies stored in the memory, different browsers have different processing methods.

The session mechanism adopts a solution that maintains the status on the server side. At the same time, we also see that because the server-side persistence scheme also needs to save an identifier on the client, the session mechanism may need to use the cookie mechanism to save the identifier. Session provides a convenient way to manage global variables.

The session is for every user. The value of the variable is stored on the server and a sessionID is used to identify which user session variable is used, this value is returned to the server when the user's browser accesses it. when the customer disables the cookie, this value may also be set to get to return to the server.

In terms of security: When you access a site that uses sessions and create a cookie on your host, it is recommended that the session mechanism on the server be safer, because it does not read the information stored by the customer.

II. session mechanism

The session mechanism is a server-side mechanism. the server uses a structure similar to a hash (or a hash) to save information.

When the program needs to create a session for a client request, the server first checks whether the client request contains a session id (called session id ), if it already exists, it indicates that a session has been created for this client. then, the server retrieves and uses this session according to the session id (a new session will be created if it cannot be retrieved ), if the client request does not contain the session id, the client creates a session and generates a session id associated with the session. the session id value should be unique, the session id is returned to the client for saving in this response.

The cookie can be used to save the session id. in this way, the browser can automatically display the id to the server according to the rules during the interaction. Generally, the cookie name is similar to SEEESIONID. However, if a cookie can be artificially disabled, there must be other mechanisms so that the session id can still be passed back to the server when the cookie is disabled.
A frequently used technology called URL rewriting is to directly append the session id to the end of the URL path. Another technique is form hidden fields. The server automatically modifies the form and adds a hidden field so that the session id can be passed back to the server when the form is submitted.

Cookie and Session can be used for Session tracking, but the process is not the same. In normal circumstances, both of them can meet the requirements, but sometimes they cannot use cookies, and sometimes they cannot use sessions.

The following describes the characteristics and applicable places of the two.

1. different access methods

Cookies can only store ASCII strings. if you want to access Unicode characters or binary data, you need to encode them first. Java objects cannot be directly accessed in cookies. To store slightly complex information, it is more difficult to use cookies.
The Session can access any type of data, including but not limited to String, Integer, List, and Map. Sessions can also be used to store Java beans and even any Java classes and objects. The Session can be viewed as a Java container class.

2. different privacy policies

The Cookie is stored in the client reader and visible to the client. some client programs may snoop, copy, and modify the content in the Cookie. The Session is stored on the server and transparent to the client. there is no risk of sensitive information leakage.
If you use cookies, we recommend that you do not write sensitive information, such as your account and password, into cookies. It is best to encrypt the Cookie information like Google and Baidu, submit it to the server, and decrypt it again to ensure that the information in the Cookie can be read by myself. If you select a Session, it will save you a lot of trouble. it is placed on the server, and any privacy in the Session can be effectively protected.

3. different validity periods

Anyone who has used Google knows that Google's login information will be valid for a long time if they have logged on to Google. You do not have to log on again every time you access the service. Google will permanently record the user's logon information. To achieve this effect, using cookies will be a good choice. You only need to set the Cookie expiration time attribute to a large number.

Because the Session depends on the Cookie named JSESSIONID, and the expiration time of the Cookie JSESSIONID defaults to-1, you only need to disable the reader and the Session will be invalid, so the Session will not be able to complete the effect of permanent information. URL address rewriting cannot be completed. In addition, if you set the Session timeout time to be too long, the more sessions the server accumulates, the more likely it will cause memory overflow.

4. Differences in server pressure

A Session is stored on the server. each user generates a Session. If a large number of concurrent access users are involved, a large number of sessions are generated, consuming a large amount of memory. Therefore, websites with high concurrent access volumes such as Google, Baidu, and Sina are unlikely to use sessions to track customer sessions.

The Cookie is stored on the client and does not occupy server resources. Cookie is a good choice if many users are reading concurrently. Cookie may be the only choice for Google, Baidu, and Sina.

5. different browser support

Cookie is supported by the client browser. If the client disables or does not support cookies, session tracking will become invalid. Conventional cookies are useless for WAP applications.

If the client browser does not support cookies, the Session and URL address must be used for rewriting. It should be noted that all the URLs used by the Session program must be rewritten. Otherwise, the Session trace will become invalid. For WAP applications, rewriting of Session + URL addresses may be the only option.

If the client supports cookies, the Cookie is valid in both the browser window and subwindow (set the expiration time to-1 ), it can also be set to valid in all Reader Windows (set the expiration time to an integer greater than 0 ). However, the Session can only be valid in the current reader window and its subwindows. If two browser windows are irrelevant, they use two different sessions. (Session coherence in different windows in IE8)

6. Differences in cross-origin support

Cookie supports cross-domain access. for example, if the domain attribute is set to ".biaodianfu.com", all domain names suffixed with ".biaodianfu.com" can access the Cookie. Cross-domain Cookie is now widely used in networks, such as Google, Baidu, and Sina. Session does not support cross-domain access. The Session is only valid within the domain name.
Using cookies or sessions alone may not achieve the desired results. In this case, try using both Cookie and Session. The combination of cookies and sessions will achieve many unexpected results in practical projects.

The above is a comparison between Cookie and Session in php, hoping 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: 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.