Tag Archives: Functions

PHP Automatic Logout – Auto Logout

This PHP function automatically logs out a user after a specified amount of inactivity.
Usage: Add this PHP code to the top of your pages
<?php
session_start();
$inactive = 30; // Set timeout minutes
$logout_redirect_url = "index.php"; // Set logout URL
auto_logout($inactive, $logout_redirect_url);
function auto_logout($inactive, $logout_redirect_url)
{
global $inactive, $logout_redirect_url;
$inactive = $inactive * 60; // Converts minutes to seconds
if (isset($_SESSION['start_time']))
{
$elapsed_time = time() - $_SESSION['start_time'];
if ($elapsed_time >= $inactive)
{
session_destroy();
header("Location: $logout_redirect_url");
}
}
$_SESSION['start_time'] = time();
}