How to set the session expiration time in php

Source: Internet
Author: User

Example: use cooikes

The code is as follows: Copy code
<? Php
Session_start ();
// Save for one day
$ LifeTime = 24*3600;
Setcookie (session_name (), session_id (), time () + $ lifeTime ,"/");
?>

PHP5 Session also provides a function session_set_cookie_params (); to set the lifetime of PHP5 Session. This function must be called before the session_start () function is called:

The code is as follows: Copy code

<? Php
// Save www.111cn.net for one day
$ LifeTime = 24*3600;
Session_set_cookie_params ($ lifeTime );
Session_start ();
?>

In php, another ini_set can be used to set session. gc_maxlifetime to set the Session lifecycle. For example:

The code is as follows: Copy code

<? Php
Ini_set ('session. Gc_maxlifetime', 3600); // Set the time
Ini_get ('session. Gc_maxlifetime'); // obtain the value set in ini.

?>

The following provides a function encapsulated by someone else, but I have not tested it. It is for reference only:

The code is as follows: Copy code

<? Php
Function start_session ($ expire = 0)
    {
If ($ expire = 0 ){
$ Expire = ini_get ('session. Gc_maxlifetime ');
} Else {
Ini_set ('session. Gc_maxlifetime', $ expire );
    }
    
If (empty ($ _ COOKIE ['phpsessid ']) {
Session_set_cookie_params ($ expire );
Session_start ();
} Else {
Session_start ();
Setcookie ('phpsessid ', session_id (), time () + $ expire );
    }
    }
?>

Usage:

Add start_session (600); // expire after 600 seconds.

 

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.