How to Change the Session Timeout in PHP

09/05/2021

Contents

In this article, you will learn how to change the session timeout in PHP.

Change PHP Session Timeout

To change the session timeout in PHP, you can use the session.gc_maxlifetime configuration directive. This directive sets the number of seconds after which session data will be seen as ‘garbage’ and cleaned up by the session garbage collector.

The session.gc_maxlifetime directive controls the maximum lifetime of a session. It is measured in seconds, and its default value is typically set to 1440 seconds (24 minutes) in the php.ini file. However, this value can be changed by modifying the php.ini file or by using the ini_set() function in your PHP script.

For example, if you want to set the session timeout to 30 minutes, you would use the following code:

php.ini:

session.gc_maxlifetime = 1800

PHP script:

<?php
  ini_set('session.gc_maxlifetime', 1800);
  session_start();
?>

Also, you can set the lifetime of a cookie in session_set_cookie_params function.

<?php
  $lifetime = 60 * 60 * 24 * 14; // 2 weeks in seconds
  session_set_cookie_params($lifetime);
  session_start();
?>

Please note that this is the maximum time that a session can exist, but it’s not the time that the session will be active. The session will be active only when the user interacts with the website by making requests or refreshing the page.