How to Expire a PHP Session After 30 Minutes

Keeping a session alive for a specific duration and then expiring it is a common requirement in PHP applications. In this article, we will explore how you can achieve this by setting the session timeout to 30 minutes. We will cover the following topics:

  1. Understanding PHP Sessions
  2. Setting the Session Timeout to 30 Minutes
  3. Destroying the Session After 30 Minutes
  4. Handling Session Expiration Events

1. Understanding PHP Sessions

Before we dive into setting session timeouts, let's understand what PHP sessions are and how they work.

A session is a way to store information about a user across multiple page requests. It allows you to store user-related data and persist it between different web pages. With sessions, you can keep track of user login status, shopping cart contents, and other relevant information.

PHP sessions work by creating a unique session identifier (also known as a session ID) for each user. The session ID is typically stored in a cookie on the user's device. When the user visits a new page, PHP reads the session ID from the cookie (or URL if cookies are disabled) and uses it to retrieve the stored session data.

Now that we have a basic understanding of PHP sessions, let's move on to setting the session timeout.

2. Setting the Session Timeout to 30 Minutes

In order to expire a PHP session after 30 minutes, we need to set the session timeout to 30 minutes. By default, PHP sessions have no built-in timeout and will continue to exist until the user closes the browser or the session is explicitly destroyed.

To set the session timeout to 30 minutes, we can use the session.gc_maxlifetime directive in the PHP configuration file (php.ini) or by modifying it dynamically using the ini_set() function.

If you have access to the php.ini file, you can find the session.gc_maxlifetime directive and set it to the desired number of seconds (1800 seconds in this case):

; php.ini
session.gc_maxlifetime = 1800
        

If you don't have access to the php.ini file, you can modify the session timeout at runtime using the ini_set() function:

<?php
// Set session timeout to 30 minutes (1800 seconds)
ini_set('session.gc_maxlifetime', 1800);
        

By setting the session.gc_maxlifetime to 1800 seconds (30 minutes), PHP will automatically destroy the session after the specified time of inactivity.

3. Destroying the Session After 30 Minutes

Setting the session timeout alone is not enough to automatically destroy the session after 30 minutes. We also need to actively check the session's last activity time and destroy it if it exceeds the specified timeout.

We can achieve this by storing the session's last activity time in a session variable and periodically checking it against the current time. If the elapsed time is greater than the session timeout, we can destroy the session using the session_destroy() function.

<?php
session_start();

// Store the last activity time
$_SESSION['last_activity'] = time();

// Check if the session has expired
if (time() - $_SESSION['last_activity'] >= 1800) {
    // Expire the session
    session_unset();
    session_destroy();
}
        

In the above code snippet:

  • We start the session using the session_start() function.
  • We store the current time in the $_SESSION['last_activity'] variable, representing the last time the session was active.
  • We check if the difference between the current time and the last activity time is greater than or equal to 1800 seconds (30 minutes).
  • If the session has expired, we use session_unset() to clear all session variables and session_destroy() to destroy the session.

With this code in place, the session will be automatically destroyed after 30 minutes of inactivity.

4. Handling Session Expiration Events

In some cases, you might need to perform certain actions when a session expires. For example, you might want to log the user out or redirect them to a specific page.

To handle session expiration events, you can use PHP's session callback functions. The session_set_save_handler() function allows you to specify callback functions that get called when various session-related events occur, including session expiration.

Here's an example of how you can use session callback functions to handle session expiration:

<?php
session_set_save_handler(
    function ($savePath, $sessionName) {
        // Custom session open logic
    },
    function () {
        // Custom session close logic
    },
    function ($sessionId) {
        // Custom session read logic
    },
    function ($sessionId, $sessionData) {
        // Custom session write logic
    },
    function ($sessionId) {
        // Custom session destroy logic
        // You can perform any actions you need here
        // For example, log the user out or redirect them to a specific page
    },
    function ($maxLifetime) {
        // Custom session garbage collection logic
    }
);

// Start the session
session_start();
        

In the above code snippet:

  • We use the session_set_save_handler() function to set our custom callback functions for session management.
  • We define empty callback functions for session open, close, read, and write.
  • We define a custom session destroy function that gets called when the session is destroyed.
  • Inside the session destroy function, we can perform any additional actions we need, such as logging the user out or redirecting them.
  • We start the session using session_start().

This approach gives you full control over session management and allows you to handle session expiration events in a customized way.

Conclusion

In this article, we covered how to expire a PHP session after 30 minutes. We learned how PHP sessions work, how to set the session timeout to 30 minutes, how to destroy the session after the specified timeout, and how to handle session expiration events.

By following the steps outlined in this article, you can implement session expiration in your PHP applications and ensure that user sessions are automatically destroyed after a specific period of inactivity.