PHP Session Validity Period

Source: Internet
Author: User
Tags php session

Session processing is a must for all Web applications. The processing of session validity in PHP is very different from other solutions. This is related to the working mechanism of PHP.

In traditional client/server applications, the network protocol can handle session failures. Whether the client closes the connection or the connection is interrupted due to a network exception, the server can be notified to trigger the connection interruption event. You only need to program the response to this event and execute the specified operation. However, for web applications, the situation is completely different. The HTTP protocol itself is stateless. That is to say, the connection is disconnected whenever the client/server completes a request/response process. After the connection is disconnected, the server does not know whether the client is "online" and sends the next request. In other words, whether the client user has closed the browser window or the user is only reading the current webpage and is ready to continue browsing in the next second, or the server is completely unable to send the next request because of Windows crash/power failure/hard disk failure/network disconnection/Earth explosion. (In HTTP 1.1, the browser can use the keep-alive parameter to notify the server not to actively disconnect the server after responding to the request, so as to achieve physical persistent connections. However, this is only a measure taken to improve the network transmission performance. HTTP is still logically stateless .) Therefore, you can only use a simulated method to determine whether the current session is valid. If a session does not send a request to the server after a period of time, the server determines that the user is "offline", the current session is invalid, and the connection interruption is triggered. To achieve this, the server needs to run a background thread to regularly scan all session information and determine whether the session has timed out.

The principle of PHP session processing is no exception, but the specific implementation method is different. This is because, due to the working mechanism of PHP, it does not have a background thread to regularly scan session information and determine whether it is invalid. The solution is that when a valid request occurs, PHP determines whether to call a GC (Garbage Collector) based on a probability ). GC is to scan all session information, and subtract the current time from the last modification time (modified date) of the session, which is the same as the configuration option session. compare the value of gc_maxlifetime. If the survival time exceeds gc_maxlifetime, delete the session. This is easy to understand, because if the GC Code is called every time a request is made, PHP's efficiency will be much lower. This probability depends on the value of the Configuration Parameter session. gc_probability/session. gc_divisor (which can be modified through the php. ini or ini_set () function ). By default, session. gc_probability = 1, session. gc_divisor = 100, that is, there is a 1% possibility to start GC. The three parameters, session. gc_maxlifetime/session. gc_probability/session. gc_divisor, can be modified through the php. ini or ini_set () function. Remember that if you use the ini_set () function, you must call ini_set () at the beginning of each page ().

This leads to another problem. gc_maxlifetime can only ensure the shortest time for session survival and cannot be saved until this time expires. The session information will be deleted immediately. Because GC is started based on probability and may not be started for a long time, a large number of sessions will still be valid after gc_maxlifetime is exceeded. Of course, the probability of such a situation is very small, but if your application requires a very accurate performance of the session, this will lead to a very serious problem. One way to solve this problem is to set the session. gc_probability/session. the probability of gc_divisor increases. If we mention 100%, this problem will be completely solved, but it will obviously have a serious impact on performance. Another method is to discard the php gc and determine the survival time of the current session in the Code. If it exceeds gc_maxlifetime, the current session will be cleared.

The default session validity period in PHP is 1440 seconds (24 minutes). That is to say, if the client does not Refresh after 24 minutes, the current session will become invalid. To modify this default value, the correct solution is to modify the configuration parameter session. gc_maxlifetime.

I used to search for a solution to this problem on the Internet and found the solution to the problem. Some users want to set "session_life_time". As far as I know, PHP does not have this parameter. Some say you want to call session_set_cookie_params or set session. cookie_lifetime, which is only used to set the survival time of the client-side cookie. In other words, this value is valid only when the survival time of the client-side cookie is smaller than the session lifetime of the server-side cookie, the maximum session lifetime on the server end cannot be exceeded. The reason is simple. When the session on the server end has expired, it makes no sense to have a longer cookie on the client end. It is also said that session_cache_expire should be called. this parameter is used to notify the browser and proxy about how long the content of the current page should be cached and has no direct relationship with the session lifetime.

It sounds like this solution is perfect. However, when you try to modify the value of session. gc_maxlifetime in practice, you may find that this parameter basically does not work and the session validity period remains the default value for 24 minutes. It may even occur, but it works normally in the development environment, but does not work on the server!

To completely solve this problem, we need to further analyze the work details of PHP.

By default, session information in PHP is saved as a text file in the temporary file directory of the system. This path is specified by the configuration parameter session. save_path. In Linux, this path is usually tmp, and in Windows it is usually C: WindowsTemp. When multiple PHP applications exist on the server, they store their session files in the same directory (because they use the same session. save_path parameter ). Similarly, these PHP applications start GC and scan all session files at a certain rate.

The problem is that GC does not differentiate sessions of different sites during operation. For example, the gc_maxlifetime of Site A is set to 2 hours, and the gc_maxlifetime of Site B is set to the default 24 minutes. When the GC of Site B is started, It scans the public temporary file directory and deletes all session files that have exceeded 24 minutes, regardless of whether they are from site A or site B. In this way, the gc_maxlifetime setting of Site A is virtually empty.

Locate the problem and solve it easily. Call the session_save_path () function at the beginning of the page. It can modify the session. save_path parameter and direct the directory of the saved session to a dedicated directory, such as tmpmyapp. In this way, the gc_maxlifetime parameter works normally.

Use a public session. save_path also causes security issues, because it means that other PHP programs on the same server can also read session files of your site, which may be used for hacker attacks. Another problem is efficiency: in a busy site, thousands of session files may exist, while many session files on different websites are stored in the same directory, whether it is reading and writing a single file or traversing all files for GC, it will undoubtedly lead to a reduction in performance. Therefore, if your PHP application runs on the same server as other PHP applications, we strongly recommend that you use your session. save_path.

Strictly speaking, this is a PHP bug. When PHP is performing GC, it should distinguish session files from different sites and apply different gc_maxlifetime values. Currently, this problem still exists in the latest PHP 5.2.X.

As mentioned above, there may be thousands of session files on a busy site. Even if the session. save_path directory of different sites is differentiated, the number of session files on a single site may still cause efficiency problems. To solve this problem, there are several feasible methods:

If PHP runs in Linux, use the ReiserFS file system to replace the default ext2/ext3 file system. ReiserFS greatly improves the access performance of a large number of small files than ext2/ext3.

Point session. save_path to a memory path. This means that the session file is read and written only in the memory, without disk operations.

Session. save_path accepts an additional N parameter, which is used to specify the level of the directory. For example, "5;/tmp" will lead to the creation of a session file like this:/tmp/4/B/1/e/3/sess_4b1e384ad74619bd212e236e52a5a174If. For more information, see: http://cn.php.net/manual/en/session.configuration.php#ini.session.save-path

The ultimate solution is to discard the PHP session processing mechanism, and use its own encoding to take over all session processing operations, which is implemented through the session_set_save_handler () function. By taking over session processing, you can save all sessions in a dedicated database (often using memory tables) to completely solve the problems caused by session files, it also facilitates session sharing and replication. This is also a common method for large PHP applications. For details about the use of the session_set_save_handler () function, I will not go into details here. It is worth mentioning that even in this way, the probability of starting GC still depends on session. gc_probability/session. gc_divisor.

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.