I have a question on how to automatically show alert message. I have set the time limit to 10s but I need to manually refresh the page then alert message will pop up. Alert message that will be display will tell the user the session is over and reload the page. Here is my code
<?php
//start session
session_start();
//database connection
$conn = mysqli_connect("localhost","root","","test");
//default timezone
date_default_timezone_set('Asia/Kuala_Lumpur');
//if user click login button
if(!empty($_POST["login"]))
{
//query table to verify inserted value
$result = mysqli_query($conn,"SELECT * FROM users WHERE username = '" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
//fetch result result row as an associative, a numeric array, or both
$row = mysqli_fetch_array($result);
//if it is true
if($row)
{
//declare a session for selected value using id and time logged in
$_SESSION["user_id"] = $row['id'];
$_SESSION['timestamp'] = time();
}
else
{
//redirect to homepage
echo '<script type="text/javascript">alert("Invalid Username or Password!");window.location = "userlogin_session.php";</script>';
}
}
//check for session timeout
if(isset($_SESSION['timestamp']))
{
//set time limit in seconds
$expireAfterSeconds = 10;
//calculate many seconds have passed since the user was last active
$secondsInactive = time() - $_SESSION['timestamp'];
//convert seconds into minutes
$expireAfter = $expireAfterSeconds / 60 ;
//check to see if time is equals or above given time limit
if($secondsInactive >= $expireAfter)
{
//kill session.
session_unset();
session_destroy();
//redirect to homepage
echo '<script type="text/javascript">alert("Session Over");window.location = "userlogin_session.php";</script>';
}
}
//if user click logout button
if(!empty($_POST["logout"]))
{
//kill session.
session_unset();
session_destroy();
}
?>