Tutorial :In PHP how do we set the expiry date of a session? [closed]


I'm new to sessions and PHP. I know how to set the expiration of a cookie. I wanted to know how is something similar done for a session.


To ensure it'll not expire before its time

If you're using cookies for sessions, you use session_set_cookie_params to set the expiration time of the corresponding cookie.

You'll also need to change session.gc-maxlifetime and quite possibly session.save_path, though it may vary if you're not using the file sessions save handler.

To ensure it'll not expire after its time

This will guarentee a minimum duration for the session, but you must also save in the session itself when it will expire and check against that to make sure the session doesn't last more than it's supposed to.

This is because:

  • The expiration date of the cookie may have been tempered with (extended by the user).
  • session.gc-maxlifetime doesn't guarentee the expired session will be garbaged collected after that period and it refers to a maximum lifetime of inactivity, not total duration.

So you have to also check server-side whether the session is valid â€" see this answer.


You could use this:

// Change the session timeout value to 30 minutes  ini_set(’session.gc_maxlifetime’, 30*60);  

You can also set other option, see doc: http://fr.php.net/manual/en/function.ini-set.php


session_start();    // 10 mins in seconds  $timeout = 600;     if(isset($_SESSION['timeout']) ) {    // Check if session timed out    $session_time = time() - $_session['timeout'];      if($session_time > $timeout)    {         // If it did, destroy it and probably logout user       session_destroy();       header("Location: logout.php");    }  }    $_SESSION['timeout'] = time();  


You can save last session seen date_time for this session and compare it when you have session activity.

But you may want use session_set_cookie_params() function and documentation for it you can find at http://php.net/manual/en/function.session-set-cookie-params.php

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »