Table of contents
Open Table of contents
Issue
You as developer need to validate session for users, one of the approach is to validate inactivity time for the user, here i show you the approach to do this using a php file and include in all the page files in your website.
Problem solving
here was the steps to get the file to validate session in PHP.
Create validation variable
First step is to create the perios inactivity variable, the follow was an option.
$inactivity_time = 5 * 60 // This was for 5 minutes = 5 * 60 seconds
Validate inactivity period
Next step for inactivity period was to verify the current time and latest activity time.
Before to show you how to validate, on the user login or user session start you need to add the follow piece of code to create the first activity of the user, this variable would be used on session validation.
$_SESSION['last_activity'] = time(); // Set current time to latest activity variable
Inactivity validation
Now after add this variable the user was created the last_activity time, now we can validate if the latest activity was inside the permitted period.
if( isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > inactivity_time))
User was inactive
If the user passed the inactivity permitted period, then you can clean all the session variables and handle the correct functionality for your website, like here was an example to redirect to login page.
session_unset(); // this clean all session variables
session_destroy(); // this destroy all data registered to a session
header("Location: " . PUBLIC_PATH . "login.php"); // this redirects to a login page on public path
exit(): // terminates the current script with default status code
User was active
If the user was on permitted period then just update the last activity variable.
$_SESSION['last_activity'] = time(); // Set current time to latest activity variable
Complete code
Here was the complete code currently use on my website to validate if user was on valid inactivity period, also i add the validation to verify if the user are logged in or not.
<?php
$inactivity_time = 5 * 60 // This was for 5 minutes = 5 * 60 seconds
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $tiempo_inactividad)) {
session_unset(); // this clean all session variables
session_destroy(); // this destroy all data registered to a session
header("Location: " . PUBLIC_PATH . "login.php"); // this redirects to a login page on public path
exit(): // terminates the current script with default status code
}
$_SESSION['last_activity'] = time(); // Set current time to latest activity variable
// Here you can add other logic to validate, here i-m validating if user was logged in.
if (!isset($_SESSION['Logged'])) {
header("Location: " . PUBLIC_PATH . "/login.php");
exit();
}