PHP session survival time

Source: Internet
Author: User
Tags php session

 The default session validity period in PHP is 1440 seconds (24 minutes) [weiweiok
Note: The default value is 180 in PhP5. 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 data library, 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. 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 the principles and steps for using permanent sessions.
    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_divisor (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_divisor = 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 GC of Site B is started, it will scan the public temporary file directory and delete 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_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 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 will be annoying. 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 will be 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!
Bytes ------------------------------------------------------------------------------------
<Title> PHP information display </title>
<? Phpinfo ()?>
Bytes ------------------------------------------------------------------------------------
Open the editor, enter the above code, and then run the program in the browser. The PHP information is displayed, as shown in 1 ). 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!
Copy the Code as follows:
Session_start ();
Ini_set ('session. save_path ','/tmp /');
// 6 hours
Ini_set ('session. gc_maxlifetime', 21600 );
// Save for 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 ...... However, the above method is sufficient for some sites that need to be stored for a long time!
Put the session into MySQL example:
Create a table in the database: Session (sesskey varchar32, expiry int11, value longtext)
Code:
The database has been connected before the code is executed.
Copy the Code as follows:
Define ('store _ session', '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, run mysql_pconnect and 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 );
I still don't understand where the open and write parameters come from.
Modify two common functions for PHP. ini configuration:
Get_cmd_var ('session. gc_maxlifetime'): obtains the value of session. gc_maxlifetime.
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.