[0006 · session] How to ensure the session is not destroyed in advance, but time and thorough destruction

session using the common two major problems:

  1. With the use of, suddenly session expired, is empty
  2. Want to completely write-off session, sometimes not necessarily be written off immediately

To solve these two problems, this gives an effective way, i.e., based on (modified and Artificial Inspect the php.ini $ _SESSION [ 'last_time']) solution.

The first step, modify the php.ini session.gc_maxlifetime, session.gc_divisor, session.gc_probability value

session.gc_maxlifetime = 14400 
  • session time to live, that is, the session file after 4 hours after generation, is considered junk files, waiting for the gc (garbage collocation) garbage collection. Here considering server performance issues, when a moderate amount of users, the default value is 1440 (24 minutes) was changed to 14400 (4 hours)
session.gc_divisor = 1000 
session.gc_probability = 1 
  • session garbage recycling probability denominator, and can be understood to perform a garbage collection run many times as session_start (), where the first and leave the default value of 1000 1
  • Note: If you use Appserv and other publishing tools, modified php.ini need to restart the service tool

The second step, when generating a session using the system needs a value, generating $ _SESSION [ 'last_time']
a working time remains, the other for 10 minutes once disconnected, as follows:

	//当前时间
	$hour = date("H");
	//during the morning
	if($hour < 12 && $hour > 6)
	{
		$_SESSION['last_time'] = strtotime("12:00:00");
	//during the afternoon
	}elseif($hour < 18 && $hour > 13){
		$_SESSION['last_time'] = strtotime("18:00:00");
	//other time
	}else{
		$_SESSION['last_time'] = time() + 60 * 10;
	}

Test code is as follows:

	if(!empty($_SESSION['last_time']))
	{
		if($_SESSION['last_time'] > time())
		{
			//session超时,但未被清空,手工执行清空
			//$_SESSION = array(); //这个大家一直在用,但不确定其是否有意义,之后将更新这里
			session_unset(); //释放内存中的session,但不删除session文件与sessionid
			session_destroy(); //删除session文件与sessionid,但不释放内存中的session
			//执行业务代码
		}else{
			//session在有效期内,执行业务代码
		}
	}else{
		//session超时,且被清空,未以防万一,再次清空一次
		//$_SESSION = array(); //这个大家一直在用,但不确定其是否有意义,之后将更新这里
		session_unset(); //释放内存中的session,但不删除session文件与sessionid
		session_destroy(); //删除session文件与sessionid,但不释放内存中的session
		//执行业务代码
	}
  • Note: This code needs to have a front session_start (), open session

At this point, the realization of the session is not destroyed in advance, but the demand on time and completely destroyed. Welcome to put forward their own views on this, we will continue to update.

Guess you like

Origin blog.csdn.net/HoD_DoH/article/details/92791415