Home > Backend Development > PHP Problem > What is the principle of php session control

What is the principle of php session control

爱喝马黛茶的安东尼
Release: 2023-02-23 12:22:02
Original
3102 people have browsed it

What is the principle of php session control

#What is session control?

Cookies and sessions are both technical means for tracking the entire session process. A session is a call between the user and the server through the browser.

Why do we need session control?

Because the HTTP protocol is stateless, the server does not know what the user did last time, which seriously hinders the implementation of interactive web applications. HTTP does not use additional means. The server does not know what the user has done. In order to do this, it needs to use cookies and sessions. The server can set or read the information contained in the cookie to maintain the state of the user's session with the server.

What is the difference between session and cookie?

Storage location, privacy policy and security, data type, validity period, server pressure, browser support, cross-domain support, data volume.

(1) Cookie is on the client side, session is on the server side

(2) Cookie is local and can be modified at will, session is more secure

(3) Cookie only supports asciII string, needs to be decoded. Session supports all data types.

(4) Cookies are stored locally and can be valid permanently. The session is on the server. After the setting is permanently valid, the sessions on the server will continue to accumulate, which will cause memory overflow.

(5) The session will be saved on the server within a certain period of time. When access increases, it will take up more of your server's performance. If you mainly consider reducing server performance, you should use cookies.

(6) Cookie needs browser support, session does not support it.

(7) Cookie supports cross-domain, but session does not support cross-domain.

(8) The storage capacity is different.

Related recommendations: "PHP Tutorial"

1. Differences in data types

Cookie can only store ASCII strings, if access is required Unicode characters or binary data need to be encoded 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 browser and are visible to the client. Some programs on the client may snoop, copy or even modify the content in the cookie. 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. If you choose Session, it will be much easier. Anyway, it is placed on the server, and any privacy in Session can be effectively protected.

3. Difference in validity period

Anyone who has used Google knows that if you have logged in to Google, the Google login information will be valid for a long time. Users do not need to log in again every time they visit, as 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 Session cannot achieve the effect of permanent validity of 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.

Cookies are stored on the client side and do 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

Cookie needs 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 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. (Related to sessions in different windows under IE8)

6. Differences in cross-domain support

Cookie supports cross-domain access. For example, if the domain attribute is set to ".biaodianfu.com", then " 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.

7. The amount of stored data is different

The data saved by a single cookie cannot exceed 4k, and many browsers limit a site to save up to 20 cookies.

Usage scenarios of session and cookies?

Store important information such as login information as SESSION; if other information needs to be retained, it can be placed in COOKIE.

How do cookies work?

1. Cookies are divided into two types

(1) Persistent cookies stored in the hard disk space in the form of files (the [Remember Password] and [Automatic Login] functions of the website are Persistent cookies)

(2) There are temporary cookies that occupy memory in the browser

2. Cookies use a solution that maintains state on the client, which is a type of session state on the client. storage mechanism. It is a small piece of text stored by the server on the local machine or a piece of data in memory, and is sent to the same server with each request.

How cookies work:

How cookies work , which requires a basic foundation of HTTP protocol.

Cookies were first described in RFC2109 (obsolete, replaced by RFC2965). Each client can hold up to 300 cookies, and each domain name can hold up to 20 cookies (in fact, most browsers now There are more than this (for example, Firefox is 50), and the size of each cookie is up to 4K, but different browsers have their own implementations. For the use of cookies, the most important thing is to control the size of cookies, do not put useless information, and do not put too much information.

No matter what server technology is used, as long as the HTTP response sent back contains a header in the following form, it is deemed that the server requires setting a cookie:

Set-cookie:name=name;expires=date;path=path;domain=domain
Copy after login

Browsers that support cookies will In response to this, a cookie file is created and saved (it may also be a memory cookie). Every time the user makes a request in the future, the browser must determine whether any of the current cookies have expired (judged based on the expires attribute) and match the The cookie information of the path attribute, if any, will be added to the request header and sent back to the server in the following form:

Cookie: name="zj"; Path="/linkage"
Copy after login

The dynamic script on the server will analyze it and handle it accordingly. Of course, you can also choose to ignore it directly.

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 adopts a solution that maintains state on the client side. It is a storage mechanism for session state on the user side. 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 processing methods for 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's 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 more secure, because it will not arbitrarily read the client's stored data. information.

How does session work?

(1) By default, all user information is stored on the server's hard disk. But you can use memcache to put this data in memory.

(2) When the client sends a request to the server and requires the server to generate a session, the server will first check whether there is a session_id in the client's cookie and whether it has expired. If there is such a session_id, the server will retrieve the server's session based on the session_id in the cookie. If there is no such session_id, the server will re-create one. PHPSESSID is an encrypted string, and its generation is performed according to certain rules. If the same client starts session_start twice, the session_id will be different.

(3) Since the solution of maintaining state on the server side also needs to save an identity on the client side, the session mechanism uses the cookie mechanism to achieve the purpose of saving the identity.

(4) Session generation The session_id is placed in the cookie. If the user disables the cookie, will the session become unusable? After disabling cookies, the session can of course be used, but the sessionid can be obtained in other ways. For example, it can be rooted at the end of the URL, or submitted to the server in the form of a form. This allows the server to understand the status of the client.

Let’s look at the principle of session again:

(1) Generate a globally unique identifier (sessionid);

(2) Open up data storage space. Generally, the corresponding data structure will be created in the memory, but in this case, once the system is powered off, all session data will be lost. If it is an e-commerce website, this kind of accident will have serious consequences. However, it can also be written to a file or even stored in a database. Although this will increase I/O overhead, the session can achieve a certain degree of persistence and is more conducive to session sharing;

(3) Send the session's globally unique identifier to the client.

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 according to the session id (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 for storage in this response.

The method of saving this session id can use cookies, 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 implementation principles 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.

The above is the detailed content of What is the principle of php session control. For more information, please follow other related articles on the PHP Chinese website!

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