Home  >  Article  >  Backend Development  >  How to set session validity period in php

How to set session validity period in php

王林
王林Original
2020-08-01 14:48:376073browse

How to set the session validity period in php: You can set the session life cycle by setting session.gc_maxlifetime. session.gc_maxlifetime refers to setting the maximum expiration time of the session.

How to set session validity period in php

In PHP, the life cycle of the Session is mainly set by setting session.gc_maxlifetime.

(Recommended tutorial: php graphic tutorial)

session.gc_maxlifetime refers to setting the maximum expiration time of the session, which means that PHP will perform its garbage collection according to a certain probability Mechanism, this mechanism refers to judging whether the current time minus the last modification time of the session file is greater than session.gc_maxlifetime, and if so, delete the session file.

Code example:

<?php 
ini_set(&#39;session.gc_maxlifetime&#39;, 3600); //设置时间 
ini_get(&#39;session.gc_maxlifetime&#39;);//得到ini中设定值 
?>

(Video tutorial recommendation: php video tutorial)

An encapsulated function is provided below for reference only.

The code is as follows:

<?php 
function start_session($expire = 0) 
{ 
 if ($expire == 0) { 
 $expire = ini_get(&#39;session.gc_maxlifetime&#39;); 
 } else { 
 ini_set(&#39;session.gc_maxlifetime&#39;, $expire); 
 } 
 if (emptyempty($_COOKIE[&#39;PHPSESSID&#39;])) { 
 session_set_cookie_params($expire); 
 session_start(); 
 } else { 
 session_start(); 
 setcookie(&#39;PHPSESSID&#39;, session_id(), time() + $expire); 
 } 
} 
?>

The above is the detailed content of How to set session validity period in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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