I'm trying to set up a time out so the user is logged out after a certain period of inactivity.
However I'm getting a redirect loop error when the user is timed out, I've concluded this can only be because the $_SESSION['last_activity'] variable is still set after the user is logged out.
So how do I clear the session?? I've included the code I'm using below, it looks good to me but isn't working..
index.php
PHP Code:
<?php
ob_start();
session_start();
// store the current time
$session_now = time();
// get the time the session should have expired
$session_limit = $session_now - 60 * 20;
// check the time of the last activity
if (isset($_SESSION['last_activity']) && $_SESSION['last_activity'] < $session_limit) {
// if too old, redirect
$url = BASE_URL . 'logout.php'; // Define the URL.
header("Location: $url");
exit();
} else {
// otherwise, set the value to the current time
$_SESSION['last_activity'] = $session_now;
}
?>
logout.php
PHP Code:
<?php
// Logs out the logged in user and redirects to them to index.php
require_once ('includes/config.inc.php');
$page_title = 'Login';
$url = BASE_URL . 'index.php'; // Define the URL.
// If no user_id session variable exists, redirect the user:
if(!isset($_SESSION['user_id'])) {
$url = BASE_URL . 'index.php'; // Define the URL.
ob_end_clean();
header("Location: $url");
exit(); // Quit the script.
} else { // Log out the user.
$_SESSION = array(); // Destroy the variables.
session_destroy(); // Destroy the session.
setcookie(session_name(), '', time()-300); // Replace the session cookie
ob_end_clean();
header("Location: $url");
exit(); // Quit the script.
}
?>