


Comparative analysis of the similarities and differences between Cookie and Session in PHP
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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
