DEV Community

Shamsuddeen Omacy
Shamsuddeen Omacy

Posted on

Ensuring Secure User Sessions: A Guide to Logging Out Users Due to Inactivity in PHP

Securely logging out users from your web app due to inactivity is an important security measure to prevent unauthorized access to sensitive data. Here are some steps you can take to securely log out users due to inactivity:

Step 1: Set session timeout

In your PHP code, set the session timeout using the session.gc_maxlifetime setting. This setting determines the maximum lifetime of a session in seconds.

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

// Start session
session_start();
Enter fullscreen mode Exit fullscreen mode

Step 2: Display warning message

Create a JavaScript function to display a warning message to users before logging them out due to inactivity. This function will be called after the session timeout has expired.

function showTimeoutWarning() {
  // Display warning message to user
  alert('Your session will expire soon. Please click OK to continue.');
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Confirm logout

Create a logout page to confirm that the user wants to log out. This page will be displayed after the session timeout has expired.

<?php
// Check if user clicked logout button
if (isset($_POST['logout'])) {
  // Invalidate session
  session_unset();
  session_destroy();

  // Clear cookies
  setcookie('PHPSESSID', '', time() - 3600, '/');

  // Redirect to login page
  header('Location: login.php');
  exit();
}
?>

<!DOCTYPE html>
<html>
<head>
  <title>Confirm Logout</title>
</head>
<body>
  <h1>Are you sure you want to log out?</h1>
  <form method="post">
    <input type="submit" name="logout" value="Log Out">
  </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 4: Invalidate session and clear cookies

In your PHP code, invalidate the user's session and clear any cookies associated with the session when logging them out due to inactivity.

// Check if session has timed out
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > ini_get('session.gc_maxlifetime'))) {
  // Invalidate session
  session_unset();
  session_destroy();

  // Clear cookies
  setcookie('PHPSESSID', '', time() - 3600, '/');

  // Redirect to logout page
  header('Location: logout.php');
  exit();
}

// Update last activity time
$_SESSION['LAST_ACTIVITY'] = time();
Enter fullscreen mode Exit fullscreen mode

Step 5: Redirect to login page

In your PHP code, redirect the user to the login page after logging them out due to inactivity.

// Redirect to login page if user is not authenticated
if (!isset($_SESSION['user_id'])) {
  header('Location: login.php');
  exit();
}
Enter fullscreen mode Exit fullscreen mode

By following these steps, you can securely log out users from your web app due to inactivity, and help prevent unauthorized access to sensitive data.

Top comments (0)