Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP set cookie lifetime

I have this function to start a secure session:

function sec_session_start() {
    $session_name = 'sec_session_id'; // Set a custom session name
    $secure = false; // Set to true if using https.
    $httponly = true; // This stops javascript being able to access the session id. 

    ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies. 
    $cookieParams = session_get_cookie_params(); // Gets current cookies params.
    session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"],     $cookieParams["domain"], $secure, $httponly); 
    session_name($session_name); // Sets the session name to the one set above.
    session_start(); // Start the php session
    session_regenerate_id(true); // regenerated the session, delete the old one.     
}

How do I set my cookies to expire whenever the user navigates away from my app or closes their browser? Basically, every time a user visits my app, they need to login again.

like image 1000
FastTrack Avatar asked Aug 09 '12 15:08

FastTrack


People also ask

How do you set cookie lifetime?

setcookie( "CookieName", "CookieValue", time() + (10 * 365 * 24 * 60 * 60) ); Note that if you set a date past 2038 in 32-bit PHP, the number will wrap around and you'll get a cookie that expires instantly.

What is the default expiration time of cookie in PHP?

The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select the directory you prefer).

How do you set cookie max age?

The setMaxAge(long expiry)method of Java HttpCookie class is used to set the maximum age of the cookie within seconds. The result with a positive value indicates that the cookie will expire after the specified time in seconds.

Can cookies not expire?

Cookies can expire. A cookie with no expiration date specified will expire when the browser is closed. These are often called session cookies because they are removed after the browser session ends (when the browser is closed). Cookies with an expiration date in the past will be removed from the browser.


1 Answers

A lifetime of 0 (which is usually the default for session cookies) does precisely what you described. See http://us3.php.net/manual/en/session.configuration.php#ini.session.cookie-lifetime

like image 170
VoteyDisciple Avatar answered Oct 11 '22 23:10

VoteyDisciple