Customizing the session Expiration Time

Source: Internet
Author: User

Customizing the session Expiration Time

Reference: http://www.jb51.net/article/52309.htm


In PHP, set php.ini, find session.gc_maxlifetime = 1440 # (PHP5 default 24 minutes).

Here you can set the expiration time. But some people say that after the setting, it doesn't seem to work!

It doesn't really work, but because the system defaults:

session.gc_probability = 1

Session.gc_divisor = 1000

Garbage collection There is a probability that 1/1000 is the session 1000 times before being recycled.

As long as you have a large number of visits, it will be able to achieve the effect of recycling.

Or you can set the value of the Session.gc_divisor,

For example: Session.gc_divisor = 1, so you can clearly see the effect of the session expires.


Set in a PHP program, as shown in the following example program:

<?php

if (!isset ($_session[' last_access ')) | | (Time ()-$_session[' last_access ')) >60)

$_session[' last_access '] = time ();

?>

If you want to set up expired, you can also implement it in your program:

<?php

unset ($_session[' last_access ');//or $_session[' last_access ']= ';

?>


The session has an expiration mechanism:

Session.gc_maxlifetime Original session expiration is a small probability event, using session.gc_probability and Session.gc_divisor respectively to determine the probability of GC in the running session The default values for Session.gc_probability and session.gc_divisor are 1 and 100, respectively. Numerator and denominator, respectively, so the GC in the session


The probability of a chance to run is 1%. If you modify these two values, you will reduce the efficiency of PHP. So this method is wrong!!

Therefore, modifying the gc_maxlifetime variable in the php.ini file can prolong the session Expiration time: (for example, we change the expiration time to 86,400 seconds)

Session.gc_maxlifetime = 86400

Then, restart your Web service (typically Apache).

When the session "Recycle" occurs:

By default, every PHP request will have a 1/100 probability of recycling, so it might simply be understood as "one recovery per 100 PHP requests". This probability is controlled by the following parameters

#概率是gc_probability/gc_divisor

session.gc_probability = 1

Session.gc_divisor = 100

Note 1: Assuming this situation is gc_maxlifetime=120, if the last modification time of a session file is 120 seconds ago, the session will still be valid until the next recovery (1/100 probability) occurs.

NOTE 2: If your session uses Session.save_path to save the session,session recycle mechanism, it is possible that the expired session file will not be processed automatically. You will need to periodically delete the expired session manually (or crontab):


The session in PHP never expires

Do not modify the program is the best way, because if you modify the program, the test department must be very depressed, then only modify the system environment configuration, is actually very simple, open the php.ini settings file, modify three lines as follows:

1, Session.use_cookies

Set this value to 1 and use a cookie to pass the SessionID

2, Session.cookie_lifetime

This represents sessionid the time that the client cookie is stored, the default is 0, which means that the browser shuts down SessionID. This is why the session of PHP cannot be used permanently! So let's set it to a number we think is big, 999999999 how, yes! That's it.

3, Session.gc_maxlifetime

This is the session data on the server side of the storage time, if more than this time, then the session data will be automatically deleted! Then we also set it to 99999999.

That's all OK, of course, if you don't believe it, just test it--set a session value after a 10-day half-month return to see if your computer is not powered down or down, you can still see this sessionid.

Of course, you may not have control of the server permissions and not as fortunate as I can modify the php.ini settings, all depend on ourselves there is a way, of course, we must use the client to store cookies, the resulting sessionid stored in the client's cookie, Set the value of this cookie and pass this value to session_id ().


function, as follows:

<?php

Session_Start (); Start session

$_session[' count ']; Register Session variable Count

Isset ($PHPSESSID)? session_id ($PHPSESSID): $PHPSESSID = session_id ();

If $phpsessid is set, the SessionID is assigned to $PHPSESSID, otherwise it is generated SessionID

$_session[' count ']++; Variable count plus 1

Setcookie (' Phpsessid ', $PHPSESSID, Time () +3156000); Store SessionID into cookies

Echo $count; Displays the value of the session variable count

?>


Session invalidation does not pass

Let's write a PHP file: <?=phpinfo (), and upload it to the server to see the configuration of the server's parameters.

Go to the session section and see that the SESSION.USE_TRANS_SID parameter is set to zero.

This parameter specifies whether transparent SID support is enabled, that is, whether the session is passed along with the URL. My personal understanding is that once this parameter is set to 0, then each URL will start a session. In this way, the page cannot be traced back to the previous page of the session, which is what we say cannot be delivered. Two pages generated two on the server side


Session file, and no association. (Here the precise principle remains to be confirmed)

So one way is to change the value of Session.use_trans_sid to 1 in the config file php.ini.

Of course, we know that not everyone has the authority to change the configuration of PHP, then what is the indirect solution?

Here are two examples to illustrate:

File 1 test1.php

<?php

Indicates that the session is marked with a user ID

session_id (SID);

Start session

Session_Start ();

Assigns the name of the session to Havi

$_session[' name ']= "Havi";

Output session and Set hyperlink to second page test2.php

echo "<a href=" test2.php "rel=" external nofollow ">". $_session[' name ']. " </a> ";

?>

test2.php

<?php

Indicates that the session is marked with a user ID

session_id (SID);

Start session

Session_Start ();

The session passed in the output test1.php.

echo "This is". $_session[' name '];

?>

So, the focus is on session_start (), preceded by session_id (SID), so when the page is converted, the server uses the session in the server session folder, which resolves the issue of delivery.

But some friends will reflect that, in this way, multiple users of the session is written in a SID, the value of the session will not play out. So there is a workaround for this problem, without adding session_id (SID), if you have configured permissions on the server's php.ini:

Output_buffering change to ON, the truth is not the table.

The second possible reason is that you do not have read permissions to the folder where the session was saved, or return to phpinfo.php to see the address saved by the session:

Session.save_path:var/tmp

So just check to see if the Var/tmp folder is writable.

Write a file: test3.php to test:

<?php

Echo Var_dump (is_writeable (Ini_get ("Session.save_path"));

?>

If you return bool (false) to prove that the file folder permission is limited, then change folders to add in the page you wrote:

Set the current directory session subfolder to save the path for the session.

$sessSavePath = DirName (__file__). ' /session/';

If the new path is readable and writable (it can be implemented by changing the folder property to 777 on FTP), let the path take effect.

if (is_writeable ($sessSavePath) && is_readable ($sessSavePath))

{

Session_save_path ($sessSavePath);

}


--------------------------------------

Reference:

Http://www.jb51.net/article/74783.htm


Set the session in PHP there are many aspects of the package has to set the value of the session or directly set the expiration, expiration and validity period, the following small series to give you friends to introduce how to use.

Let's take a look at how the session is set in PHP.ini, open php.ini, find the following in the session Settings section, the code is as follows:


Session.save_path = "N;/path"

Session.save_path = "C:/temp" #此处以你自己设定的路径为准

This setting provides us with a multi-level hash of the session's directory, where "N" indicates the number of levels to set, and the following "/path" indicates the path to the root directory where the session file is stored, such as the format we set as below:

Session.save_path = "2; C:/temp "

The above settings indicate that we have PHP session file for two levels of directory storage, each level of the directory is 0-9 and a-Z a total of 36 alphanumeric for the directory name, so that the directory of the session can reach 36*36, a total of 1332 folders, I believe as a single server, This is completely enough if your system architecture is designed to be shared with multiple servers


Session data, you can increase the directory level to level 3 or more.

Session Expiration Time setting

Continue the session topic in PHP, in PHP mainly by setting the Session.gc_maxlifetime to set the session life cycle, such as the following code:

<?php

Ini_set (' Session.gc_maxlifetime ', 3600); Set the time

Ini_get (' session.gc_maxlifetime ');//Get Set value in INI

?>

Here is a function that someone else has encapsulated, but I have not tested it for reference only, the code is as follows:

<?php

function start_session ($expire = 0)

{

if ($expire = = 0) {

$expire = Ini_get (' session.gc_maxlifetime ');

} else {

Ini_set (' Session.gc_maxlifetime ', $expire);

}

if (Emptyempty ($_cookie[' Phpsessid ')) {

Session_set_cookie_params ($expire);

Session_Start ();

} else {

Session_Start ();

Setcookie (' Phpsessid ', session_id (), time () + $expire);

}

}

?>

How to use:

Add Start_session (600),//600 seconds later expires.

The session never Expires method

Open the PHP.ini settings file and modify the three line as follows:

1, Session.use_cookies

Set this value to 1 and use a cookie to pass the SessionID

2, Session.cookie_lifetime

This represents sessionid the time that the client cookie is stored, the default is 0, which means that the browser shuts down SessionID. This is why the session of PHP cannot be used permanently! So let's set it to a number we think is big, 999999999 how, yes! That's it.

3, Session.gc_maxlifetime

This is the session data on the server side of the storage time, if more than this time, then the session data will be automatically deleted! Then we also set it to 99999999.

That's all OK, of course, if you don't believe it, just test it--set a session value after a 10-day half-month return to see if your computer is not powered down or down, you can still see this sessionid.

Of course, you may not have control of the server permissions and not as fortunate as I can modify the php.ini settings, all depend on ourselves there is a way, of course, you must use the client to store cookies, the resulting sessionid stored in the client's cookie, set the value of this cookie, and then the This value is passed to the session_id ()


function in the following way:

<?php

Session_Start (); Start session

$_session[' count ']; Register Session variable Count

Isset ($PHPSESSID)? session_id ($PHPSESSID): $PHPSESSID = session_id ();

If $phpsessid is set, the SessionID is assigned to $PHPSESSID, otherwise it is generated SessionID

$_session[' count ']++; Variable count plus 1

Setcookie (' Phpsessid ', $PHPSESSID, Time () +3156000); Store SessionID into cookies

Echo $count; Displays the value of the session variable count

?>

The above is the specific procedure of the PHP setup session, the content of the session setting value or directly set the expiration, expiration and expiration, I hope that everyone's learning to help.



-------------------------------------

Reference:

Http://www.jb51.net/article/17882.htm

The duration of the session in PHP is 1440 seconds (24 minutes) By default, that is, if 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 mini-net


Station, there seemed no need to be 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


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 determines whether to start a GC 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)


(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. In the same way, these PHP applications


Will start the GC at a certain rate and scan 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. Solve this


One way to do this is to raise 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 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 the 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.

--

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 you do not have a database 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 little confused, open,write where those parameters come from.

Modify the two common functions of the php.ini configuration:

Get_cfg_var (' Session.gc_maxlifetime '): Gets the value of Session.gc_maxlifetime

Ini_set (' session.cookie_lifetime ', ' 0 '): Sets the value of Session.cookie_lifetime to 0.




Customizing the session Expiration 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.