Home > php教程 > PHP开发 > body text

How to accurately set session expiration time in php

高洛峰
Release: 2016-12-24 09:19:15
Original
1291 people have browsed it

In most cases, we use the default setting for the session expiration time, but for some cases with special requirements, we can set the session expiration time.

In this regard, you can set php.ini in PHP and find session.gc_maxlifetime = 1440 #(PHP5 default is 24 minutes)
Here you can set the expiration time at will. But some people say that after setting it, it doesn’t seem to work!
In fact, it’s not that it doesn’t work, but because the system defaults:

session.gc_probability = 1
session.gc_divisor = 1000
Copy after login

garbage collection has a probability, 1/1000 means that only one session will be recycled 1000 times.
As long as your visit volume is large, you can achieve the effect of recycling.
Or you can also set the value of session.gc_divisor,
For example: session.gc_divisor = 1, so that you can clearly see the effect of SESSION expiration

What we most commonly use is to set it in the php program, as shown in the following example program:

<?php
if(!isset($_SESSION[&#39;last_access&#39;])||(time()-$_SESSION[&#39;last_access&#39;])>60)
$_SESSION[&#39;last_access&#39;] = time();
?>
Copy after login

That’s it. If you want to set the expired value, you can also do it in the program:

<?php
unset($_SESSION[&#39;last_access&#39;]);// 或 $_SESSION[&#39;last_access&#39;]=&#39;&#39;;
?>
Copy after login

session has an expiration mechanism :

session.gc_maxlifetime It turns out that session expiration is a small probability event. Session.gc_probability and session.gc_divisor are used to determine the probability of running gc in the session. The default values ​​of session.gc_probability and session.gc_divisor are 1 and 100 respectively. are the numerator and denominator respectively, so the probability of gc running in the session is 1%. If you modify these two values, it will reduce the efficiency of PHP. So this approach is wrong! !
Therefore, modifying the gc_maxlifetime variable in the php.ini file can extend the session expiration time: (for example, we modify the expiration time to 86400 seconds)
session.gc_maxlifetime = 86400
Then, restart your web service (usually apache) will do.

When does session "recycling" occur:

By default, for every php request, there will be a 1/100 probability of recycling, so it may be simply understood as "one recycling occurs for every 100 php requests" . This probability is controlled by the following parameters
#The probability is gc_probability/gc_divisor

session.gc_probability = 1
session.gc_divisor = 100
Copy after login

Note 1: Assume that in this case gc_maxlifetime=120, if a session file was last modified 120 seconds ago, then the next recycling (1 /100 probability) occurs, this session is still valid.

Note 2: If your session uses session.save_path to save the session elsewhere, the session recycling mechanism may not automatically process expired session files. At this time, you need to delete expired sessions manually (or crontab) regularly:

cd /path/to/sessions; find -cmin +24 | xargs rm
Copy after login

The session in PHP never expires

The best way is not to modify the program, because if the program is modified, the testing department will be very depressed, so just It is actually very simple to modify the system environment configuration. Open the php.ini settings file and modify the three lines as follows:

1. session.use_cookies

Set this value to 1 and use cookies to pass sessionid

2. session. cookie_lifetime

This represents the time that the SessionID is stored in the client cookie. The default is 0, which means that the SessionID will be invalidated as soon as the browser closes... It is because of this that the PHP session cannot be used permanently! So let's set it to a number we think is big, how about 999999999, that's ok! that's all.

3. session.gc_maxlifetime

This is the time that Session data is stored on the server side. If this time is exceeded, the Session data will be automatically deleted! So let's also set it to 99999999.

That's it, everything is ok. Of course, if you don't believe it, just test it and see - set up a session and come back after 10 days and a half. If your computer does not have a power outage or downtime, you can still See this sessionid.

Of course, it is also possible that you do not have permission to control the server and are not as lucky as me to modify the php.ini settings. We have a way to rely on ourselves. Of course, we must use the client to store cookies and store the obtained sessionID. Go to the cookie on the client, set the value of this cookie, and then pass this value to the session_id() function. The specific method is as follows:

<?php
session_start(); // 启动Session
$_SESSION[&#39;count&#39;]; // 注册Session变量Count
isset($PHPSESSID)?session_id($PHPSESSID):$PHPSESSID = session_id();
// 如果设置了$PHPSESSID,就将SessionID赋值为$PHPSESSID,否则生成SessionID
$_SESSION[&#39;count&#39;]++; // 变量count加1
setcookie(&#39;PHPSESSID&#39;, $PHPSESSID, time()+3156000); // 储存SessionID到Cookie中
echo $count; // 显示Session变量count的值
?>
Copy after login


Session failure will not be passed

Let’s write a php file first: < ;?=phpinfo()?>, pass it to the server to see the server parameter configuration.
Go to the session section and see that the session.use_trans_sid parameter is set to zero.
This parameter specifies whether to enable transparent SID support, that is, whether the session is passed along with the URL. My personal understanding is that once this parameter is set to 0, a session will be opened for each URL. In this way, subsequent pages cannot track the session of the previous page, which is what we call undeliverable. The two pages generate two session files on the server side and are not related. (The precise principle here needs to be confirmed)
So one way is to change the value of session.use_trans_sid to 1 in the configuration file php.ini.

Of course we know that not everyone has the authority to change the configuration of php, so what other indirect solutions are there?
Two examples will be used to illustrate:
File 1 test1.php

<?php
//表明是使用用户ID为标识的session
session_id(SID);
//启动session
session_start();
//将session的name赋值为Havi
$_SESSION[&#39;name&#39;]="Havi";
//输出session,并设置超链接到第二页test2.php
echo "<a href="test2.php" rel="external nofollow" >".$_SESSION[&#39;name&#39;]."</a>";
?>
Copy after login


File 2: test2.php

<?php
表明是使用用户ID为标识的session
session_id(SID);
//启动session
session_start();
//输出test1.php中传递的session。
echo "This is ".$_SESSION[&#39;name&#39;];
?>
Copy after login


所以,重点是在session_start();前加上session_id(SID);,这样页面转换时,服务器使用的是用户保存在服务器session文件夹里的session,解决了传递的问题。
不过有朋友会反映说,这样一来,多个用户的session写在一个SID里了,那Session的价值就发挥不出来了。所以还有一招来解决此问题,不用加session_id(SID);前提是你对服务器的php.ini有配置的权限:
output_buffering改成ON,道理就不表了。
第二个可能的原因是对服务器保存session的文件夹没有读取的权限,还是回到phpinfo.php中,查看session保存的地址:

session.save_path: var/tmp
Copy after login


所以就是检查下var/tmp文件夹是否可写。
写一个文件:test3.php来测试一下:

<?php
echo var_dump(is_writeable(ini_get("session.save_path")));
?>
Copy after login


如果返回bool(false),证明文件夹写权限被限制了,那就换个文件夹咯,在你编写的网页里加入:

//设置当前目录下session子文件夹为session保存路径。
$sessSavePath = dirname(__FILE__).&#39;/session/&#39;;
//如果新路径可读可写(可通过FTP上变更文件夹属性为777实现),则让该路径生效。
if(is_writeable($sessSavePath) && is_readable($sessSavePath))
{
session_save_path($sessSavePath);
}
Copy after login

   


更多php中实现精确设置session过期时间的方法相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!