How can I track how long a user stays on a page before they request another or simply leave the site?
Basically, I want to do a check, if a user stays on the page for 20 minutes or longer, then do something.
I believe this would require php and javascript, but I am not exactly sure how to accomplish it.
Maybe using this $_SERVER in php to get the time of execution, and then get a timestamp when the user clicks somewhere else and simply compare the two?
You can do all this with simple javascript. 
For a single page:
window.setTimeout(function(){
// Do stuff after 20 minutes of loading the page
// Then using jQuery you can call a PHP script to do stuff like so:
$.ajax({
     url: '/myScript.php',
     method: 'POST',
     success: function(result){
        //The request was successful and the output is stored in a variable: result
     },
     complete: function(){
        //Do stuff when the request is completed (Ignores if success or not)
     },
     beforeSend: function(){
        //Do something before the request is sent
     }
});
}, 20 * 60 * 1000); //This is in milliseconds that's why I use the equation 
For multiple pages: 
I suggest you set a cookie with the time a user hits a page and on each page check if the cookie exists. If it exists run a query every x ammount of seconds to see if the 20 minutes have passed since the cookie has been created. 
For full Ajax documentation head to: http://api.jquery.com/jQuery.ajax/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With