Session lifecycle in PHP

Source: Internet
Author: User
Tags cron script
The session lifecycle in PHP first describes the process from the beginning to the end of session creation.

When the program needs to create a session for a client request, the server first checks whether the client contains a session id, this is called the session id (obtain method session_id (). If a session id is included, the client has already created a session, the server retrieves the value of this session according to the session id. if the client does not contain the session id, the client first requests the server or manually clears the cached file, the client creates a session and generates a session id associated with the session. Generally, the session id value is unique and the encrypted string is not repeated, this session id will be returned to the client for saving in this response.

When will a session be created?

Usually (usually) is created when the browser sends the first request to the server, and it occupies a certain amount of memory space. Therefore, the session is closed as much as possible without any need.

When will a session be deleted?

In general, Sessions are deleted under these circumstances:

First, use the session_destroy () reset function to manually delete it;

Second, the interval between the last session activity time and the current time exceeds the time set for session Timeout. third, the server process is stopped.

How can I delete a session when the browser is closed?

Theoretically, http is a stateless protocol, so the server does not know when the client will turn off the browser, in addition, PHP does not have a related function to obtain this information, but this problem can be solved by using the webpage special effect code window. oncolose monitors the closing action of the browser, and then sends a request to the server using Ajax to delete the session. However, this solution does not completely solve the problem, the reason is that in some cases, such as a browser crash, a sudden power failure, or a user crash, the system cannot respond.

How can I set to make the session automatically expire (delete) after a period of time )?

Session_start () is the beginning of the session mechanism. it has a certain probability to enable garbage collection, because the session is stored in the file, and the garbage collection of PHP itself is invalid. SESSION collection (deletion) is to delete the file, this probability is based on php. ini configuration depends, but some systems are session. gc_probability = 0, which means that the probability is 0, but garbage collection (delete session) is implemented through the cron script ).

The default session validity period in PHP is 1440 seconds (24 minutes, note: The default value in php5 is 180 minutes]. that is to say, if the client is not refreshed for more than 24 minutes, the current session will become invalid. Obviously, this cannot meet the needs.

A known method is to use session_set_save_handler to take over all session management tasks. generally, session information is stored in the database, so that all expired sessions can be deleted through SQL statements, precisely control the validity period of the session. This is also a common PHP-based method for large websites. However, small websites do not seem to have to work hard.

However, the life cycle of a general Session is limited. if the user closes the browser, the Session variable cannot be saved! So how can we achieve the permanent life of the Session?

As you know, sessions are stored on the server side. you can obtain the user's file based on the SessionID provided by the client, read the file, and obtain the variable value, sessionID can use the Cookie of the client or Query_String of the Http1.1 protocol (that is, the "?" To the server, and then the server reads the Session directory.

To realize the permanent life of a Session, first you need to know about the Session settings of php. ini (open the php. ini file, in the "[Session]" section ):

1. session. use_cookies: The default value is "1", which indicates that SessionID is transmitted using cookies, and Query_String is used for transmission;

2. session. name: the name of the variable stored by SessionID, which may be Cookie or Query_String. the default value is "PHPSESSID ";

3. session. cookie_lifetime: This indicates the time when SessionID is stored in the Cookie on the client. the default value is 0, indicating that the session id will be voided as soon as the browser closes the session id ...... This is why the Session cannot be used permanently!

4. session. gc_maxlifetime: the time when Session data is stored on the server. if this time is exceeded, the Session data is automatically deleted!

There are still a lot of settings, but this is related to this article. The following describes how to use permanent Session principles and steps.

As mentioned above, the server reads Session data through SessionID, but generally the SessionID sent by the browser does not exist after the browser is closed. Therefore, we only need to manually set the SessionID and save it, no. If you have operation permissions on the server, it is very easy to set up, but you only need to perform the following steps:

1. set "session. use_cookies" to 1. enable the Cookie to store the SessionID. However, the default value is 1, which generally does not need to be modified;

2. change "session. cookie_lifetime" to positive infinity (of course there are no positive infinity parameters, but there is no difference between 999999999 and positive infinity );

3. set "session. gc_maxlifetime" to the same time as "session. cookie_lifetime;

The PHP document clearly states that the parameter for setting the session validity period is session. gc_maxlifetime. You can modify this parameter in the php. ini file or through the ini_set () function. The problem is that after multiple tests, modifying this parameter does not work, and the session validity period remains the default value for 24 minutes.

Due to the working mechanism of PHP, it does not have a daemon thread to regularly scan session information and determine whether it is invalid. When a valid request occurs, PHP will use the global variable session. gc_probability/session. gc_pisor (you can also use php. ini or ini_set () function to modify) to determine whether to start a GC (Garbage Collector ).

By default, session. gc_probability = 1, session. gc_pisor = 100, that is, there is a 1% possibility to start GC. GC is used to scan all session information and subtract the last modification time (modified date) of the session from the current time. compare the gc_maxlifetime parameter. if the survival time exceeds gc_maxlifetime, delete the session.

So far, everything works normally. Why is gc_maxlifetime invalid?

By default, session information is saved as a text file in the temporary file directory of the system. In Linux, this path is usually \ tmp, and in Windows it is usually C: \ Windows \ Temp. When there are multiple PHP applications on the server, they will save their session files in the same directory. 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. Modify the session. save_path parameter, or use the session_save_path () function to direct the Directory of the session to a dedicated directory. the gc_maxlifetime parameter works properly.

Strictly speaking, is this a PHP bug?

Another problem is that gc_maxlifetime can only ensure the shortest time for session survival. it cannot be saved until this time expires and the session information will be deleted immediately. GC is started by chance and may not be started for a long time. Therefore, a large number of sessions will still be valid after gc_maxlifetime is exceeded.

One way to solve this problem is to set the session. gc_probability/session. the probability of gc_pisor increases. if 100% is mentioned, this problem will be completely solved, but it will obviously have a serious impact on performance. Another method is to determine the survival time of the current session in the code. if the time exceeds gc_maxlifetime, the current session is cleared.

However, if you do not have the server operation permission, it is quite troublesome. you need to rewrite the SessionID through the PHP program to save Session data permanently. Check the php.net function manual and you can see the "session_id" function: If no parameter is set, the current SessionID is returned. if a parameter is set, the current SessionID is set to the given value.

You can use the permanent Cookie and the "session_id" function to save the permanent Session data!

However, for convenience, we need to know the "session. name ", but generally users do not have the permission to view the server's php. ini settings, but PHP provides a very good function "phpinfo", which can be used to view almost all PHP information!

    

Open the editor, enter the above code, and then run the program in the browser. The PHP information will be displayed. There is a "session. name" parameter. this is the server "session. name" we need, which is generally "PHPSESSID ".

After recording the SessionID name, we can store Session data permanently!

     

In addition, for setting the survival time of the php session, some netizens wrote a very good method on the internet. here we will share the code:

      

The usage is also very simple, for example:

       

Note: In fact, real permanent storage is impossible, because the Cookie storage time is limited, and the server space is limited ...... However, the above method is sufficient for some sites that need to be stored for a long time!

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.