PHP
Web Development
Session Management
Cookies
Coding Tips

How do I expire a PHP session after 30 minutes?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

PHP sessions provide a way to store user-specific data across multiple page requests, which is especially useful in web applications needing to maintain state across various interactions. However, managing the lifecycle of a session, particularly its expiration, is crucial for maintaining security and resource efficiency. This article will focus on how to expire a PHP session after 30 minutes of inactivity.

Understanding PHP Sessions

Before diving into the specifics of expiring sessions, it's important to understand what a PHP session is and how it works. When a session starts, PHP generates a unique session ID which is stored in a cookie on the user's browser. This ID is sent to the server with each request, allowing PHP to retrieve and store data uniquely for each user.

Setting Up a PHP Session Expiration

PHP does not automatically manage the expiration of session data based on inactivity. Therefore, you need to implement this feature. Here are the step-by-step details:

1. Configuring the Session Timeout

PHP offers a few configuration directives to manage how sessions are handled:

  • session.gc_maxlifetime: This configuration sets the maximum life of session data in seconds. After this period, stored data will be seen as 'garbage' and potentially deleted by the garbage collection process.
  • session.cookie_lifetime: This sets the lifetime of the session cookie in seconds.
Server Configuration

For a session that expires after 30 minutes of inactivity, set session.gc_maxlifetime to 1800 seconds.

php
ini_set('session.gc_maxlifetime', 1800);

Remember, these settings alone might not enforce session expiration based on inactivity precisely as the garbage collector (GC) might not run exactly at the 30-minute mark.

2. Implementing Inactivity-based Session Expiration

To effectively ensure that the session expires after 30 minutes of inactivity, you should implement a manual method:

php
1session_start();
2
3if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
4    // request 30 minates ago
5    session_unset();     // unset $_SESSION variable for the runtime
6    session_destroy();   // destroy session data completely
7}
8$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time

Here, $_SESSION['LAST_ACTIVITY'] records the timestamp of the last activity. Each request updates this timestamp. If the current time minus the last recorded activity time exceeds 1800 seconds (30 minutes), the session is destroyed.

Security Considerations

When implementing session timeouts, consider the following security practices:

  • Avoid storing sensitive information directly in sessions if possible.
  • Always regenerate the session ID after logging in to prevent session fixation:
php
session_regenerate_id(true);
  • Use secure cookies with HTTPS to prevent interception:
php
session_set_cookie_params(['secure' => true, 'httponly' => true]);

Comparison Table

Here’s a comparison of settings that directly and indirectly influence session expiration:

PHP ConfigurationDescriptionRecommended Value
session.gc_maxlifetimeMax lifetime for session data (in seconds)1800
session.cookie_lifetimeLifetime of the session cookie (in seconds)0 (session)
session.gc_probabilityProbability that the GC process starts1
session.gc_divisorThe divisor that gc_probability is compared against100

Conclusion

Properly managing session expiration is essential for creating secure and efficient web applications. By setting the appropriate configurations and adding custom checks for last activity, you can ensure that PHP sessions expire after 30 minutes of inactivity. Always remember to combine these mechanisms with general security best practices such as using HTTPS and regenerating session IDs post-authentication.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions