Comparative analysis of the similarities and differences between Cookie and Session in PHP

PHPz
Release: 2018-10-11 15:10:26
Original
1788 people have browsed it

Let everyone have a deeper understanding of Cookies and Sessions, and provide inspiration for their flexible use in their own development work.

1. Cookie mechanism

Cookies are small pieces of text stored by the server on the local machine and sent to the same server with each request. IETF RFC 2965 HTTP State Management Mechanism is a general cookie specification. The web server sends cookies to the client using HTTP headers. On the client terminal, the browser parses these cookies and saves them to a local file. It automatically binds these cookies to any request to the same server.

Specifically, the cookie mechanism uses a solution that maintains state on the client side. It is a storage mechanism for session state on the user side, and it requires the user to turn on cookie support on the client side. The role of cookies is an effort to solve the stateless defects of the HTTP protocol.
Orthodox cookie distribution is achieved by extending the HTTP protocol. The server adds a special line of instructions to the HTTP response header to prompt the browser to generate the corresponding cookie according to the instructions. However, pure client-side scripts such as JavaScript can also generate cookies. The use of cookies is automatically sent to the server in the background by the browser according to certain principles. The browser checks all stored cookies. If the declared scope of a cookie is greater than or equal to the location of the resource to be requested, the cookie is attached to the HTTP request header of the requested resource and sent to the server. The content of

cookie mainly includes: name, value, expiration time, path and domain . The path and domain together form the scope of the cookie. If the expiration time is not set, it means that the lifetime of this cookie is during the browser session. When the browser window is closed, the cookie disappears. This type of cookie that lasts for the duration of the browser session is called a session cookie. Session cookies are generally not stored on the hard disk but in memory. Of course, this behavior is not specified by the specification. If an expiration time is set, the browser will save the cookies to the hard disk. If you close and open the browser again, these cookies will still be valid until the set expiration time is exceeded. Cookies stored on the hard drive can be shared between different browser processes, such as two IE windows. Different browsers have different ways of handling cookies stored in memory.

The session mechanism uses a solution that maintains state on the server side. At the same time, we have also seen that since the solution of maintaining state on the server side also needs to save an identity on the client side, the session mechanism may need to use the cookie mechanism to achieve the purpose of saving the identity. Session provides a convenient way to manage global variables.

Session is for each user. The value of the variable is stored on the server. A sessionID is used to distinguish which user session variable it is. This value is returned to the server through the user's browser when accessing. 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 that uses session and create a cookie on your machine, it is recommended that the session mechanism on the server side be safer because it will not arbitrarily read the client's stored data. information.

2. Session mechanism

The session mechanism is a server-side mechanism. The server uses a structure similar to a hash table (or may use a hash table) to Save information.

When the program needs to create a session for a client's request, the server first checks whether the client's request already contains a session identifier (called session id). If it does, it means that it has been created before. This client has created a session, and the server will retrieve the session based on the session id and use it (if it cannot be retrieved, it will create a new one). If the client request does not include the session id, a session will be created for the client and a session with this will be generated. The session id associated with the session. The value of the session id should be a string that is neither repeated nor easy to find patterns to counterfeit. This session id will be returned to the client in this response for storage.

Cookie can be used to save this session ID, so that during the interaction process, the browser can automatically display this identification to the server according to the rules. Generally, the name of this cookie is similar to SEEESIONID. But cookies can be artificially disabled, and there must be other mechanisms to still pass the session id back to the server when cookies are disabled.
A frequently used technique is called URL rewriting, which is to append the session id directly to the end of the URL path. There is also a technique called form hidden fields. That is, 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.

Both Cookie and Session can perform session tracking, but the principles of completion are different. Under normal circumstances, both can meet the needs, but sometimes Cookie cannot be used, and sometimes Session cannot be used.

The following is a comparison of the characteristics and applicable situations of the two.

1. Differences in access methods

Cookies can only store ASCII strings. If you need to access Unicode characters or binary data, you need to encode them first. Cookies cannot directly access Java objects. To store slightly more complex information, it is more difficult to use cookies.
Session can access any type of data, including but not limited to String, Integer, List, Map, etc. Java Beans or even any Java classes, objects, etc. can also be stored directly in the Session, which is very convenient to use. Session can be regarded 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 programs on the client The contents of cookies may be snooped, copied or even modified. The Session is stored on the server and is transparent to the client, so there is no risk of sensitive information being leaked.
If you choose cookies, a better way is to try not to write sensitive information such as account passwords in cookies. It is best to encrypt the cookie information like Google and Baidu, and then decrypt it after submitting it to the server to ensure that only the person can read the information in the cookie. It would be much easier if you choose Session. Since it is placed on the server anyway, any privacy in Session can be effectively protected.

3. Differences in validity

Everyone who has used Google knows that if you have logged in to Google, then the Google login The information is valid for a long time. Users do not need to log in again every time they visit, Google will permanently record the user's login information. To achieve this effect, using cookies would be a better choice. Just set the cookie's expiration time attribute to a very, very large number.

Because Session relies on a cookie named JSESSIONID, and the default expiration time of Cookie JSESSIONID is -1, the Session will become invalid as long as the browser is closed, so the Session cannot achieve the effect of permanent validity of the information. It cannot be accomplished using URL address rewriting. And if the session timeout is set too long, the more sessions the server will accumulate, the easier it will be to cause memory overflow.

4. Differences in server pressure

Session is stored on the server side, and each user will generate a Session. If there are a lot of users accessing concurrently, a lot of Sessions will be generated, consuming a lot of memory. Therefore, websites with extremely high concurrent visits such as Google, Baidu, and Sina are unlikely to use Session to track user sessions.

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

5. Differences in browser support

Cookies need to be supported by the client browser. If the client disables cookies or does not support cookies, session tracking will be invalid. Regarding applications on WAP, regular cookies are of no use.

If the client browser does not support cookies, Session and URL address rewriting need to be used. It should be noted that all URLs that use the Session program must be rewritten, otherwise Session tracking will be invalid. For WAP applications, Session URL address rewriting may be its only option.

If the client supports cookies, the cookie can be set to be valid in this browser window and sub-windows (set the expiration time to -1), or it can be set to be valid in all browser windows (set the expiration time) time is set to some integer greater than 0). But Session can only be valid within this reader window and its sub-windows. If two browser windows are independent of each other, they will use two different Sessions. (Session is related to different windows under IE8)

6. Differences in cross-domain support

Cookie supports cross-domain access, for example, the domain attribute If set to ".biaodianfu.com", all domain names with the suffix ".biaodianfu.com" can access this cookie. Cross-domain cookies are now commonly used on the Internet, such as Google, Baidu, Sina, etc. Session will not support cross-domain name access. Session is only valid within the domain name where it is located.
Only using Cookie or only using Session may not achieve the desired effect. At this time you should try to use Cookie and Session at the same time. The combination of Cookie and Session will achieve many unexpected effects in practical projects.

The above is the difference and comparison between Cookie and Session in php. I hope it will be helpful to everyone's learning. For more related tutorials, please visit A complete set of video tutorials on PHP programming from entry to mastery

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template