PHP Session Expiration session.gc_maxlifetime_php Tips

Source: Internet
Author: User
Tags current time php session phpinfo sessions
One known way to work is to use Session_set_save_handler to take over all session management, typically storing session information in a database so that all expired sessions can be deleted through SQL statements. Control the duration of the session precisely. This is also a large web site based on PHP commonly used methods. However, the general small Web site, it seems not necessary so multi-point.
But the life of the general session is limited, if the user closed the browser, you can not save the variable session! So how can you achieve the permanent life of the session?
As you know, the session is stored on the server side, according to the SessionID provided by the client to get the user's file, and then read the file, get the value of the variable, SessionID can use the client's cookie or Http1.1 protocol Query_ String (that is, the "?" of the URL that is accessed) Later) to the server, and then the server reads the directory of the session ...
To achieve the permanent lifetime of the session, you first need to know about the php.ini settings (open php.ini file, in the [Session] section):
1, Session.use_cookies: The default value is "1", on behalf of SessionID use cookies to pass, the other is the use of query_string to pass;
2, Session.name: This is sessionid stored variable name, may be cookies, may also 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 on the void ... This is why the session cannot be used permanently!
4, Session.gc_maxlifetime: This is the session data stored on the server side of the 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 the principle and procedure of using permanent session.
Previously said, the server through the SessionID to read the session data, but the General browser transfer SessionID after the browser is closed, then we only need to set up the SessionID and save, can not ...
If you have the right to operate the server, setting this is very, very simple, just the following steps are required:
1, the "Session.use_cookies" set to 1, open the cookie store SessionID, but the default is 1, generally do not have to modify;
2, the "session.cookie_lifetime" Change to positive infinity (of course, there is no positive infinite parameters, but 999999999 and positive infinity is no difference);
3, the "Session.gc_maxlifetime" set to and "Session.cookie_lifetime" the same time;
In the PHP documentation, it is clear that the parameter that sets the session lifetime is session.gc_maxlifetime. You can modify this parameter either in the php.ini file or through the Ini_set () function. The problem is that after a lot of testing, modifying this parameter basically does not work, the session is still valid for 24 minutes of the default value.
Because of the working mechanism of PHP, it does not have a daemon thread that periodically scans the session information and determines whether it is invalidated. When a valid request occurs, PHP is based on the value of the global variable Session.gc_probability/session.gc_divisor (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% probability that the GC will start. The work of the GC is to scan all session information, using the current time minus the last modification time of the session (modified date), compared to the session.gc_maxlifetime parameter, if the survival time has exceeded gc_ Maxlifetime, the session is deleted.
So far, everything is working fine. Then why is there a situation where gc_maxlifetime is invalid?
By default, session information is stored in the system's temporary file directory as a text file. Under Linux, this path is typically \tmp, and is typically C:\Windows\Temp under Windows. When there are multiple PHP applications on the server, they keep their session files in the same directory. Similarly, these PHP applications will start the GC at a certain rate, scanning all session files.
The problem is that GC does not differentiate between sessions of different sites when it is working. For example, site A's gc_maxlifetime is set to 2 hours, and Site B's gc_maxlifetime is set to the default 24 minutes. When the GC at Site B is started, it scans the public temporary files directory and deletes all session files that are more than 24 minutes away, regardless of whether they come from site A or B. In this way, the site A's gc_maxlifetime settings are in a fake.
Find out where the problem is, and it's easy to solve. 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 parameters work properly.
Strictly speaking, is this a bug in PHP?
Another problem is that gc_maxlifetime can only guarantee the shortest time of session survival, not be able to save in more than this time after the sessions information will be deleted immediately. Because the GC is started on a probability basis and may not be started for a long time, a large number of sessions will still be valid after gc_maxlifetime.
One way to solve this problem is to increase the probability of session.gc_probability/session.gc_divisor, and if you mention 100%, you will solve the problem completely, but obviously it will have a serious impact on performance. Another method is to determine the lifetime of the current session in your code, and if you exceed Gc_maxlifetime, empty the current session.
But if you do not have the right to operate the server, it is more cumbersome, you need to rewrite the SessionID through the PHP program to achieve permanent session data preservation. Check php.net's function manual, you can see the "session_id" function: If no parameters are set, then the current SessionID will be returned, if the parameters are set, the current SessionID will be set to the given value ...
As long as the use of permanent cookies plus the "session_id" function, you can achieve permanent session data saved!
But for convenience, we need to know the server settings "Session.name", but the general user does not have the right to view the server's php.ini settings, but PHP provides a very good function "phpinfo", use this to view almost all of the PHP information!
------------------------------------------------------------------------------------
<title>php Related Information Display </title>
<?phpinfo ()?>
------------------------------------------------------------------------------------
Open the editor, enter the code above, and then run the program in the browser to see the relevant information about PHP (as shown in Figure 1). One of the "session.name" parameters, this is the server we need "Session.name", is generally "PHPSESSID".
After you have noted the name of the SessionID, we will be able to implement a permanent session data store!
The code is as follows:
Copy Code code as follows:

Session_Start ();
Ini_set (' Session.save_path ', '/tmp/');
6 Head
Ini_set (' Session.gc_maxlifetime ', 21600);
Save one day
$lifeTime = 24 * 3600;
Setcookie (Session_name (), session_id (), time () + $lifeTime, "/");

Postscript:
In fact, the real permanent storage is not possible, because the cookie storage time is limited, and the server space is limited ... But for some need to save time longer site, the above method is enough!
Put the session into the MySQL example:
Database table: Session (Sesskey Varchar32, expiry int11, value Longtext)
Code
The database has been connected before code execution.
The code is as follows:
Copy Code code as follows:

Define (' store_sessions ', ' MySQL ');
if (store_sessions = = ' MySQL ') {
if (! $SESS _life = Get_cfg_var (' session.gc_maxlifetime ')) {
$SESS _life = 1440;
}
function _sess_open ($save _path, $session _name) {
If the database is not connected, you can perform mysql_pconnect,mysql_select_db here
return true;
}
function _sess_close () {
return true;
}
function _sess_read ($key) {
$value _query = mysql_query ("Select value from sessions where Sesskey = '". Addslashes ($key). "' and expiry > '. Time (). "'");
$value = mysql_fetch_array ($value _query);
if (Isset ($value [' value '])) {
return $value [' value '];
}
return false;
}
function _sess_write ($key, $val) {
Global $SESS _life;
$expiry = time () + $SESS _life;
$value = $val;
$check _query = mysql_query ("SELECT count (*) as total from sessions where Sesskey = '". Addslashes ($key). "'");
$check = mysql_fetch_array ($check _query);
if ($check [' Total '] > 0) {
Return mysql_query ("update sessions set expiry = '". Addslashes ($expiry). "', value = '". Addslashes ($value). "' where Sesskey = '". Addslashes ($key). "'");
} else {
return mysql_query (insert into sessions values (' "). Addslashes ($key). "', '" . Addslashes ($expiry). "', '" . Addslashes ($value). "')");
}
}
function _sess_destroy ($key) {
return mysql_query ("Delete from sessions where Sesskey = '". Addslashes ($key). "'");
}
function _sess_gc ($maxlifetime) {
mysql_query ("Delete from sessions where expiry <".) Time (). "'");
return true;
}
Session_set_save_handler (' _sess_open ', ' _sess_close ', ' _sess_read ', ' _sess_write ', ' _sess_destroy ', ' _sess_gc ');
}
Danoo_session_name (' Dtvsid ');
Danoo_session_save_path (session_write_directory);

Still a bit don't understand, open,write those parameters where come.
Modify the two common functions of the php.ini configuration:
Get_cfg_var (' Session.gc_maxlifetime '): Get the value of Session.gc_maxlifetime
Ini_set (' session.cookie_lifetime ', ' 0 '): Set the value of Session.cookie_lifetime to 0.

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.