The life cycle of a session under PHP

Source: Internet
Author: User
Tags session id php session sessions cron script

Let's start with the beginning and end of the session creation process.

When a program needs to create a session for a client's request, the server first checks to see if the client already contains a session ID, which we call session IDs (Get Method session_id ()), if it contains a session The ID indicates that the client has created a session before, and the server retrieves the value of the session according to the session ID, and if the client does not contain the session ID, indicating that the client first requested the server or manually purged the cache file, create a Session and generate a session ID associated with this session, in general, the value of session ID is not duplicated, and the encrypted string, this session ID will be returned to the client in this response to save.

When was the session created?

Usually (usually) is created when the browser makes the first request to the server, and it takes up a certain amount of memory space, so you can close the session as often as possible without unnecessary conditions.

When was the session deleted?

Normally, the session will be deleted in these cases:

One is manually deleted using the Session_destroy () reset function;

Second, the session's last active time distance from the current time is longer than the time of the session timeout setting; Third, the server process is stopped.

How do I delete a session when my browser is closed?

Theoretically, it is not possible to do this, HTTP is a stateless protocol, so the server does not know when the client shuts down the browser, and PHP does not have a phase-off function to obtain this information, but this problem can also be resolved, is to use the Web effect code window.oncolose To monitor the browser's close action, and then use Ajax to send a request to the server to delete the session, but this approach does not completely solve the problem, because in some cases such as browser crashes, sudden power outages, user crashes and so on can not respond.

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

Session_Start () is the beginning of the session mechanism, it has a certain probability to turn on garbage collection, because the session is stored in the file, PHP itself garbage collection is invalid, the session of the recovery (delete) is to delete the file, This probability is based on the configuration of the php.ini, but some systems are session.gc_probability = 0, which means that the probability is 0, instead of a cron script to implement garbage collection (that is, delete session).

The duration of the session in PHP is 1440 seconds (24 minutes, note: The default is 180 points in php5), that is, the client does not refresh for more than 24 minutes, the current session will be invalidated. Obviously, this is not enough to meet the needs.

A known method is to use Session_set_save_handler, take over all the session management work, usually the session information is stored in the database, so that the SQL statement can be used to delete all the expired session, Control the duration of the session precisely. This is also a common method for large Web sites based on PHP. However, the general small website, does not seem necessary so belabour.

However, the life of the general session is limited, if the user closed the browser, you can not save the session variables! So how can we achieve the permanent life of the session?

As you know, the session is stored on the server side, according to the client-provided SessionID to get the user's files, and then read the file, get the value of the variable, SessionID can use the client's cookie or Http1.1 protocol Query_ String (the "?" of the URL that is visited Later) to the server, and then the server reads the session directory.

To achieve the permanent lifetime of the session, you first need to know about the php.ini settings for the session (open the PHP.ini file, in the [Session] section):

1, Session.use_cookies: The default value is "1", on behalf of SessionID using cookies to pass, the other is the use of query_string to pass;

2, Session.name: This is sessionid stored variable name, may be a cookie, it may be query_string to pass, the default value is "PHPSESSID";

3, Session.cookie_lifetime: This represents SessionID in the client cookie storage time, the default is 0, on behalf of the browser a close SessionID is void ... This is why the session cannot be used permanently!

4, Session.gc_maxlifetime: This is the session data in the server-side storage time, if more than this time, then the session data will be automatically deleted!

There are a lot of settings, but this is related to this article, the following is how to use the permanent session of the principles and procedures.

As mentioned earlier, the server through the SessionID to read the session data, but the General browser transfer SessionID after the browser is closed, then we just need to set SessionID and save the human, not just. If you have permission to operate the server, it is very, very simple to set up, just the following steps:

1, the "Session.use_cookies" set to 1, open the cookie storage SessionID, but the default is 1, generally do not change;

2, the "Session.cookie_lifetime" to the positive infinity (of course, no positive infinity parameters, but 999999999 and positive infinity is no difference);

3, the "Session.gc_maxlifetime" set to "Session.cookie_lifetime" the same time;

It is clearly stated in the PHP documentation that the parameters for setting the session expiration date are session.gc_maxlifetime. You can modify this parameter in the php.ini file, or through the Ini_set () function. The problem is that, after many tests, modifying this parameter basically does not work, and the session expiration time remains at the default value of 24 minutes.

Because of PHP's working mechanism, it does not have a daemon thread to periodically scan the session information and determine if it is invalid. When a valid request occurs, PHP session.gc_probability/session.gc_divisor the value of the global variable (which can also be modified by the php.ini or Ini_set () function). To decide whether to start a GC (garbage Collector).

By default, session.gc_probability = 1,session.gc_divisor = 100, which means that there is a 1% possibility to start the GC. The GC's job is to scan all session information, subtracting the last modification time of the session (modified date) with the current time, and comparing it with the Session.gc_maxlifetime parameter if the lifetime has exceeded GC_ Maxlifetime, delete the session.

So far, it's all working. Then why does it happen that Gc_maxlifetime is invalid?

By default, session information is saved in the temporary file directory of the system as a text file. Under Linux, this path is typically \tmp, which is typically C:\Windows\Temp under Windows. When there are multiple PHP applications on the server, they will keep their session files in the same directory. Similarly, these PHP applications will launch the GC at a certain probability, scanning all session files.

The problem is that when the GC is working, it does not differentiate between sessions at different sites. For example, site A's gc_maxlifetime is set to 2 hours, and Site B's gc_maxlifetime is set to the default of 24 minutes. When the GC of Site B starts, it scans the common temporary files directory and removes all session files that are more than 24 minutes, regardless of whether they come from site A or B. In this way, site A's gc_maxlifetime setting is no more than a dummy.

Finding the problem is a simple solution. Modify the Session.save_path parameter, or use the Session_save_path () function to point the directory where the session is saved to a dedicated directory, and the Gc_maxlifetime parameter is working properly.

Strictly speaking, is this a bug in PHP?

Another problem is that gc_maxlifetime can only guarantee the shortest time that the session will survive, and not be able to save the session information immediately after it has been deleted. Because the GC is started by chance and may not be started for a long period of time, a large number of sessions will still be valid after more than Gc_maxlifetime.

One way to solve this problem is to increase the odds of session.gc_probability/session.gc_divisor, and if you mention 100%, it will solve the problem completely, but it will obviously have a serious impact on performance. Another way is to judge the current session's lifetime in code and empty the current session if the gc_maxlifetime is exceeded.

But if you do not have the server operation permissions, it is more troublesome, you need to rewrite the PHP program SessionID to achieve permanent session data preservation. Check the Php.net function manual, you can see the "session_id" this function: if the parameter is not set, then the current SessionID will be returned, if the parameter is set, the current SessionID is set to the given value.

As long as the permanent cookie with the "session_id" function, you can achieve the permanent session data saved!

But for convenience, we need to know the server settings "Session.name", but the general user does not have permission to view the server's php.ini settings, but PHP provides a very good function "phpinfo", use this can see almost all the PHP information!

<?phpphpinfo ();

Open the editor, enter the code above, and then run the program in your browser to see information about PHP. There is a "session.name" parameter, this is the server we need "Session.name", is generally "PHPSESSID".

After we have written down the name of the SessionID, we can achieve a permanent session data storage!

<?phpsession_start (); Ini_set (' Session.save_path ', '/tmp/');//6 head ini_set (' Session.gc_maxlifetime ', 21600);// Save one day $lifetime = 3600;setcookie (Session_name (), session_id (), time () + $lifeTime, "/");

In addition, to set the lifetime of the PHP session, online to see a netizen wrote a very good method, here will share the code:

<?phpfunction start_session ($expire =0) {if ($expire ==0) {$expire =ini_get (' Session.gc_maxlifetime ');} Else{ini_set (' Session.gc_maxlifetime ', $expire);} if (Empty ($_cookie[' Phpsessid ')) {session_set_cookie_params ($expire); Session_Start ();} Else{session_start (); Setcookie (' Phpsessid ', session_id (), time () + $expire);}}

The method of use is also very simple, for example:

<?php start_session (600);//600 second expires

PostScript: In fact, the real permanent storage is impossible, because the cookie save time is limited, and the server space is limited ... But for some sites that need to be kept longer, the above method is enough!

The life cycle of a session under PHP

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.