Skip to main content

Adjusting PHP Session Timeout: A Step-by-Step Guide

How to change the session timeout in PHP

Changing the session timeout in PHP can be done by adjusting the session's lifetime settings. PHP sessions rely on two parameters to manage their timeout: the session.gc_maxlifetime directive and the cookie_lifetime setting. Here’s how you can do it:

Step 1: Modify session.gc_maxlifetime
The session.gc_maxlifetime directive specifies the maximum lifetime of session data, in seconds, before it’s considered garbage and removed by the garbage collector.

Add the following code to your PHP script:
PHP:
ini_set('session.gc_maxlifetime', 3600); // 3600 seconds = 1 hour

Step 2: Adjust Session Cookie Lifetime

To ensure the session persists in the browser for the desired duration, you should also set the session.cookie_lifetime value.

PHP:
ini_set('session.cookie_lifetime', 3600); // 3600 seconds = 1 hour

Step 3: Start the Session

Ensure you call session_start() after these settings:

PHP:
ini_set('session.gc_maxlifetime', 3600);
ini_set('session.cookie_lifetime', 3600);
session_start();


Step 4: Update php.ini (Optional)

If you want these settings to be applied globally, you can modify the php.ini file. Look for the following directives:

session.gc_maxlifetime = 3600
session.cookie_lifetime = 3600


Additional Notes:

The session.gc_maxlifetime value dictates how long session data is stored on the server.

If the session data is removed from the server before the cookie expires, the session will end prematurely.



Comments