Skip to content

Automatic Logout after 15 minutes of inactive in php

To automatically log out a user after 15 minutes of inactivity in PHP, you can use the session mechanism provided by PHP. Here is an example of how you can accomplish this:

  1. Start a new session at the beginning of your PHP script using the session_start() function. Ensure it is placed before any HTML output to avoid "headers already sent" warnings.
  2. Set a timer when the user logs in or accesses a page by setting a session variable with the current time, for example: $_SESSION['last_activity'] = time();
  3. On every page load, check the time difference between the current time and the last activity time. If the difference is greater than 15 minutes (900 seconds), log the user out by destroying the session and redirecting them to the login page.

Example code:

Example of automatic Logout after 15 minutes of inactivity in PHP

php
<?php
session_start();

// Check if last activity was set
if (isset($_SESSION['last_activity']) && time() - $_SESSION['last_activity'] > 900) {
  // last request was more than 15 minutes ago
  session_destroy(); // destroy session data in storage
  header("Location: login.php"); // redirect to login page
  exit; // stop script execution
}
$_SESSION['last_activity'] = time(); // update last activity time stamp
?>

Note: In a production application, $_SESSION['last_activity'] is typically initialized when the user successfully logs in, rather than on every page load. Place this code at the top of each page where you want to enforce the auto-logout feature.

Dual-run preview — compare with live Symfony routes.