Questions about the validity of the PHP session

Source: Internet
Author: User
Tags php session phpinfo
The duration of the session in PHP is 1440 seconds (24 minutes) By default (Weiweiok Note: The default is 180 points in php5), that is, the client does not refresh for more than 24 minutes and the current session is 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 that's what this article is about, and here's how to use the permanent session principle and procedure.
As mentioned earlier, the server through the SessionID to read the session data, but the General browser transfer of SessionID after the browser is closed, then we only need to set SessionID and save the human, not can ...
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_pisor 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_pisor = 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_pisor, 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!
------------------------------------------------------------------------------------
<title>php Related Information Display </title>
<?phpinfo ()?>
------------------------------------------------------------------------------------
Open the editor, enter the code above, and run the program in the browser, and see information about PHP (1). 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!

The code is 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 impossible, because the cookie storage time is limited, and the server space is limited ... But for some sites that need to be kept longer, the above method is enough!
Put the session into MySQL's example:
Database built-in table: Session (Sesskey Varchar32, expiry int11, value Longtext)
Code
The database was connected before the code was executed.

The code is 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 there is no database connected, you can do mysql_pconnect,mysql_select_db return true here;} 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 little bit confused, open,write those parameters where to come. Modify the two common functions of the php.ini configuration: Get_cfg_var (' Session.gc_maxlifetime '): Get session.gc_maxlifetime value Ini_set (' Session.cookie_ Lifetime ', ' 0 '): Sets 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.