I want to find how much time has passed from the beginning to the end of the visit on page. I have a theory which is that, function get the time which comes by end of load, then when user leaved function also get leaving time and it calculates this times yet I do not know how to do this.
Get time using javascript when page loads and store the variable in session, and detect the page close event in js and store it in another variable so that you have the page load and unload time in two variables.
PHP is a server-side language, so your code only runs on the server. You can however use JavaScript to repeatedly run some code that invokes a PHP script that updates a last_seen
value in a session variable for the page.
For example you could try something like this...
Example PHP snippet in home_page.php
(PHP part)
<?php
$pn = "home_page";
session_start(); //needed for $_SESSION
$_SESSION["visit"][pn]=["first_seen"=>time(),"last_seen"=>time()];
?>
Example JavaScript snippet in home_page.php
(JavaScript part, assuming JQuery)
<script>
var pn = "home_page";
setInterval(function(){ // every 1 second
$.get( "time_keeper.php?page="+pn); //don't care about success
}, 1000); // precision of 1 second
</script>
Example time_keeper.php
PHP script
<?php
session_start(); //needed for $_SESSION
$_SESSION["visit"][$_GET["page"] ?? "404"]["last_seen"]=time()];
?>
Example of a see_time.php
PHP script that outputs the time spent on a specific page
<?php // usage: `see_time.php?page=home_page
session_start(); //needed for $_SESSION
$t=$_SESSION["visit"][$_GET["page"] ?? "404"]];
$z=$t["last_seen"]-$t["first_seen"];
echo "You've been there for $z seconds.";
?>
home_page
is the name of your page: change it to be uniqe for every additional page, as needed.