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.
  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.

Watch a course Learn object oriented PHP

Example code:

<?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_unset(); // unset $_SESSION variable for the run-time
  session_destroy(); // destroy session data in storage
  header("Location: login.php"); // redirect to login page
}
$_SESSION['last_activity'] = time(); // update last activity time stamp
?>

This is just an example code, you have to place it in the relevant pages where you want to implement the auto logout feature.