How to set session timeout in php

You should implement a session timeout of your own. Both options mentioned by others (session.gc_maxlifetime and session.cookie_lifetime) are not reliable. I'll explain the reasons for that.

First:

session.gc_maxlifetime
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up. Garbage collection occurs during session start.

But the garbage collector is only started with a probability of session.gc_probability divided by session.gc_divisor. And using the default values for those options (1 and 100 respectively), the chance is only at 1%.

Well, you could simply adjust these values so that the garbage collector is started more often. But when the garbage collector is started, it will check the validity for every registered session. And that is cost-intensive.

Furthermore, when using PHP's default session.save_handler files, the session data is stored in files in a path specified in session.save_path. With that session handler, the age of the session data is calculated on the file's last modification date and not the last access date:

Note: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won't have problems with filesystems where atime tracking is not available.

So it additionally might occur that a session data file is deleted while the session itself is still considered as valid because the session data was not updated recently.

And second:

session.cookie_lifetime
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. […]

Yes, that's right. This only affects the cookie lifetime and the session itself may still be valid. But it's the server's task to invalidate a session, not the client. So this doesn't help anything. In fact, having session.cookie_lifetime set to 0 would make the session’s cookie a real session cookie that is only valid until the browser is closed.

Conclusion / best solution:

The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request:

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    // last request was more than 30 minutes ago
    session_unset();     // unset $_SESSION variable for the run-time 
    session_destroy();   // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

Updating the session data with every request also changes the session file's modification date so that the session is not removed by the garbage collector prematurely.

You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:

if (!isset($_SESSION['CREATED'])) {
    $_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
    // session started more than 30 minutes ago
    session_regenerate_id(true);    // change session ID for the current session and invalidate old session ID
    $_SESSION['CREATED'] = time();  // update creation time
}

Notes:

  • session.gc_maxlifetime should be at least equal to the lifetime of this custom expiration handler (1800 in this example);
  • if you want to expire the session after 30 minutes of activity instead of after 30 minutes since start, you'll also need to use setcookie with an expire of time()+60*30 to keep the session cookie active.

The inactivity of a registered user is checked by the session timeout. When a user login into a website then a session creates for that user and the session is destroyed when the user logout or closes the browser. The session timeout is used to set the time limit for the inactivity of the user. Suppose, if the session timeout limit is set to 60 seconds and the user is inactive for 60 seconds then the session of that user will be expired and the user will require to log in again to access the site. The way to set or update the session timeout in PHP has shown in this tutorial.

Session Handling in PHP

The session_start() function is used to create a new session for the user. The default session name is PHPSESSID and it is used to check the session exists or not. If no cookie or session information is found then a new session will be generated for the user, otherwise, the current session will be used for the user.

Setting Session Timeout

The timeout limit of the session can be set by setting the value of two directives in the php.ini file or using the ini_set() function in the PHP script. The directives are given below.

  1. session.gc_maxlifetime
  2. It is used to set the time limit in seconds to store the session information in the server for a long time.

  3. session.cookie_lifetime
  4. It is used to set the expiration time limit for the PHPSESSID cookie.

The ways to set the session timeout value in PHP for handling a user’s session have been shown in this part of the tutorial by using multiple examples.

Example-1: Set session timeout value using PHP directives

Create a PHP file with the following script to know the way of setting session timeout by using PHP directives and handling sessions based on the directive values. The ini_set() function has been used in the script to set the value of the session.gc_maxlifetime and session.cookie_lifetime directives. The duration of the session has been set to 2 seconds for testing purposes. The superglobal variable $_COOKIE array has been used here to handle the session. The new session will be generated for the user when the script will execute in the browser and after two seconds the session will be expired.

//Set the session timeout for 2 seconds

$timeout = 2;

//Set the maxlifetime of the session

ini_set( "session.gc_maxlifetime", $timeout );

//Set the cookie lifetime of the session

ini_set( "session.cookie_lifetime", $timeout );

//Start a new session

session_start();

//Set the default session name

$s_name = session_name();

//Check the session exists or not

if(isset( $_COOKIE[ $s_name ] )) {

    setcookie( $s_name, $_COOKIE[ $s_name ], time() + $timeout, '/' );

    echo "Session is created for $s_name.
"
;

}

else

    echo "Session is expired.
"
;

?>

Output:

The following output will appear after executing the above script for the first time. The output shows the default session user name, PHPSESSID.

How to set session timeout in php

The following output will appear if the page is refreshed after 2 seconds.

How to set session timeout in php

Example-2: Set session timeout value using $_SESSION array

Create a PHP file with the following script to set the session timeout value using the PHP superglobal variable, $_SESSION. The time duration of the session has been set to 5 seconds for testing purposes. Next, the request time of the user for the page has stored in a variable named $time. When the time duration between the $time variable and the user’s last activity will be more than 5 seconds, then the current session of the user will be destroyed and a new session will be generated. The session_unset() and session_destroy() functions have used in the script to destroy the session.

//Start a new session

session_start();

//Set the session duration for 5 seconds

$duration = 5;

//Read the request time of the user

$time = $_SERVER['REQUEST_TIME'];

//Check the user's session exist or not

if (isset($_SESSION['LAST_ACTIVITY']) &&

   ($time - $_SESSION['LAST_ACTIVITY']) > $duration) {

    //Unset the session variables

    session_unset();

    //Destroy the session

    session_destroy();

    //Start another new session

    session_start();

    echo "New session is created.
"
;

}

else

    echo "Current session exists.
"
;

//Set the time of the user's last activity

$_SESSION['LAST_ACTIVITY'] = $time;

?>

Output:

The following output will appear after executing the above script for the first time.

How to set session timeout in php

The following output will appear if the page is refreshed after 5 seconds.

How to set session timeout in php

Example-3: Set session timeout value using $_SESSION array and time() function

Create a PHP file with the following script to set the session timeout value using PHP superglobal variable, $_SESSION, and the built-in PHP function, time(). The time() function returns the current timestamp value of the system. The time duration of the session has been set to 600 seconds (10 minutes) in the script.

The $_SESSION[‘start’] has been used to store the starting time of the session. When the time duration between the current time and the session starting time will be more than 10 minutes, then the current session of the user will be destroyed. The session_unset() and session_destroy() functions have been used in the script as the previous example to destroy the session.

//Start a new session

session_start();

//Check the session start time is set or not

if(!isset($_SESSION['start']))

{

    //Set the session start time

    $_SESSION['start'] = time();

}

//Check the session is expired or not

if (isset($_SESSION['start']) && (time() - $_SESSION['start'] >600)) {

    //Unset the session variables

    session_unset();

    //Destroy the session

    session_destroy();

    echo "Session is expired.
"
;

}

else

    echo "Current session exists.
"
;

?>

Output:

The following output will appear after executing the above script for the first time. The expired message will be displayed if the page is refreshed after 10 minutes.

How to set session timeout in php

Conclusion

Three different ways to set the session timeout value for handling a user’s session in PHP have been shown in this tutorial. The PHP users will get the basic concept of implementing the user’s session by using $_COOKIE and $_SESSION variables and be able to apply it in their script after reading this tutorial.

About the author

How to set session timeout in php

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

How do I set session timeout?

Procedure.
Log on as the admin user with the password defined for PORTAL. ... .
Click Servers > Server Type > WebSphere Application Servers > WebSphere Portal..
Click Container Settings > Session management > Set Timeout..
Enter the desired timeout value in minutes..
Click OK..
Click Save..

How is session timeout implemented in PHP?

Set Session Timeout in PHP.
Use the session_unset() and session_destroy() Functions to Set the Session Timeout in PHP..
Use the unset() Function to Set the Session Timeout in PHP..
Use the session_regenerate_id() Function to Change the Current Session ID in PHP..

Can we set time for session in PHP?

The timeout limit of the session can be set by setting the value of two directives in the php. ini file or using the ini_set() function in the PHP script. The directives are given below. It is used to set the time limit in seconds to store the session information in the server for a long time.

How do I expire a PHP session after 30 minutes?

if you want to expire the session after 30 minutes of activity instead of after 30 minutes since start, you'll also need to use setcookie with an expire of time()+60*30 to keep the session cookie active.