[Solved]: PHP sessions expiring too soon
  John Mwaniki /   31 Mar 2023

[Solved]: PHP sessions expiring too soon

PHP sessions are an essential part of web development as they enable developers to store and access information across multiple pages.

Some of the common applications of PHP sessions include:

  • User Authentication
  • Shopping Carts
  • Personalization

However, sometimes PHP sessions expire too soon, causing users to lose their data and forcing them to log in or add items to the cart again. This can be frustrating for users and can negatively impact the user experience.

In this article, we will cover some of the causes of PHP sessions expiring too soon and provide solutions to fix the issue.

What causes PHP sessions to expire too soon?

Below are some of the reasons why the sessions may seem to expire too soon:

  • Session Timeout Configuration: By default, PHP sessions are set to expire after 1440 seconds (24 mins) of inactivity. This duration can be changed in the php.ini, .htaccess, or PHP files. If this value is set too low, the sessions will expire too soon before the users are done with their activities.
  • Inactivity of Users: If users do not actively participate in the session for a timeframe longer than the session timeout duration, that can also lead to session expiration before they have finished their activity.
  • Server Load: If the server is under heavy load or has too many active sessions, it may not be able to keep all the sessions active, leading to some expiring too soon.
  • Expired Cookies: Though the user information in PHP sessions is stored on the server, the session ID is stored in a cookie on the user's computer, so that the server can identify the user in subsequent requests. If the browser is configured to delete cookies when it is closed or after a certain period of time, the session will expire prematurely.
  • Network Interruptions: Another reason why PHP sessions can expire too soon is due to network interruptions. If the connection between the client and the server is lost or interrupted, the session can be lost, leading to expiration.
  • Shared Session Directory: Session files on the server are cleaned up by the garbage collector based on the value in the session.gc_maxlifetime directive. If different websites have different values of this directive but share the same directory for storing the session data, then the garbage collector uses the minimum value to clean the data. Since by default PHP stores all session files in the same directory, other PHP processes running on the same server can set a shorter expiration time and cause their session data to be removed together with yours.

How to fix PHP sessions expiring too soon

Below are several ways you can fix this issue.

Increasing duration in session timeout settings

You can increase the session timeout settings via the php.ini file or directly in PHP files.

Below is how you can increase the session timeout to 1 hour from the default 24 minutes by adding these lines at the very beginning of all PHP files that use sessions.

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

If the pages are many, you can just create a file, add these lines and then add it at the top of the files using the include() function. This will enable easy editing if you want to change the session duration.

Alternatively, you can adjust the session timeout in the php.ini file as below.

session.gc_maxlifetime = 3600

Reduce the frequency of garbage collection

Every time a new session is started, there's a chance that garbage collection will happen. When garbage collection happens, it expires/trashes any session files that haven't been accessed in more than the session.gc_maxlifetime.

You can reduce the probability of garbage collection happening on every session initialization by configuring the session.gc_probability and session.gc_divisor directives. The default value for session.gc_probability is 1, while that of session.gc_maxlifetime is 100.

The probability is calculated using gc_probability/gc_divisor, e.g. 1/100 means there is a 1% chance that the garbage collection process starts on each request.

You can check and change these values in the php.ini file like in the example below to have a low probability.

session.gc_probability = 1
session.gc_divisor = 100

Setting a longer cookie lifetime

To prevent premature expiration of sessions due to cookies, set the cookie expiration time to a longer period. This period should be greater than, or at least equal to your session.gc_maxlifetime directive. You can set the cookie expiration time to one week as follows:

<?php
ini_set('session.cookie_lifetime', 604800); // 1 Week
session_start();
?>

Setting session.cookie_lifetime value to 0 will keep the session active until the browser is closed.

Setting a custom session directory

To prevent other sites/scripts running on the same machine as yours from setting a shorter session expiration time, you need to set your own session directory.

Create a new folder in your user home directory (outside of your webroot) that PHP has read/write access to. Then set the session.save_path directive to this new directory.

For instance, if your site resides in the "/home/username/public_html" directory in the cPanel file manager, you can create a folder like "/home/username/sessions" and ensure it has (or set) proper permissions (ie 755).

Make sure you set this path along with the session.gc_maxlifetime with each and every request before calling the session_start() function.

Then have these lines at the top of your PHP scripts

<?php
ini_set('session.save_path', '/home/username/sessions');
ini_set('session.gc_maxlifetime', 3600);
session_start();
?>

Alternatively, you can set this in your php.ini file. In cPanel, specify the full path via the MultiPHP INI Editor or directly in the php.ini file in the File Manager.

session.save_path = "/home/username/sessions"
session.gc_maxlifetime = 3600

Remember to replace "username" in the path with your actual username in the file manager.

Conclusion

PHP sessions essential in web development and expiring too soon can be frustrating and inconvenient for users. In this article, we have covered several ways in which you can fix this issue.