I have like an if/else statement which checks if the user is still logged in, else display message saying they need to log in. This is included just in case the session has expired. Now what I also have in the else statement is a mysqli code where it will perform a quesry to delete any rows in Session_Complete and Session table where the TeacherId belongs to the user which was logged in and where the Session_Complete is 0. Now this doesn’t work and this is really obvious because obviously the session has been expired meaning that the teacher is not logged in as their details have been destroyed when the session has been expired and thus it cannot recognize which teacher is logged so the query can’t delete an rows.
So my question is that if somebody was trying to tackle the same problem where the qwnt a query to be performed if the user has been logged out due to a session expire, then how would you be able to do it so that just before the session has expired it would somehpw get the TeacherId, $userid of the teacher that was logged in, so then it can be used in the query, while displaying the message that the user needs to login?
Below is the current if/else statement:
if ((isset($username)) && (isset($userid))){ //checks the logged in teacher's username and userid
//whole page code here
}else{
echo "Please Login to Access this Page | <a href='./teacherlogin.php'>Login</a>";
$incomplete = 0;
$deletesession = " DELETE session, session_complete FROM Session AS session
LEFT JOIN Session_Complete AS session_complete
ON session_complete.SessionId = session.SessionId
WHERE (session.TeacherId = ? AND Complete = ?) ";
if (!$delete = $mysqli->prepare($deletesession)) {
// Handle errors with prepare operation here
}
//Dont pass data directly to bind_param store it in a variable
$delete->bind_param("ii",$userid, $incomplete);
$delete->execute();
if ($delete->errno) {
// Handle query error here
}
$delete->close();
}
?>
The only thing you can do is keep track of either the expected expiry time of the session, based on how long you’ve set the session cookie to last, or the last activity time of the user, and store that in the database record.
You’ll have to set up a cron job to sweep up the session table every so often, and check for sessions that are past their expiry time. If you can’t use a cron job for whatever reason, you can set your regular code to randomly call the session garbage collector every so many views (depending on your typical number of visitors).
You could also try something like checking IP addresses and User-Agent headers, and try correlate those with a session, but that’s pretty error prone and I wouldn’t recommend it.