I would like to mix javascript events with php functionality to kill sessions on inactivity.
The idea is that if 15 minutes go by without clicking on the content, the session will be closed.
I have an event as soon as the page loads that saves the time in which the user accesses the content in a php variable:
$('document').ready(function(){
<?php
$firstTime = new DateTime();
echo "console.log('".$firstTime->format('H:i:s')."');";
?>
});
And then I have a function that is executed with an onClick event on the content, and that creates another variable to get the time that the user is interacting. But when I display it by console, the hours are the same:
function clickWarning() {
<?php
$lastTime = new DateTime();
echo "console.log('".$lastTime->format('H:i:s')."');";
?>
}
Why? Should I handle time solely with javascript?
What is happening to you is that PHP , being a server-side language, is executed before Javascript which is client-side.
This causes it to basically ignore the Javascript functions that are determining when the variable has to get the value (the functions
onclick
anddocument.ready
) since when the page loads the first thing that happens is that all the PHP is executed obtaining your variable the same value in the twice that you give it value, since they are executed almost at the same time.The most correct way to do it would be through an AJAX function that calls a PHP that returns the date. In this way you could call said function either from the
document.ready
or the eventonclick
obtaining the values you need.