For a project I need a timer in PHP such that starts when first page opens (say 1.php) and stops when I go to second page (say 2.php). How I can do this in PHP?
Asked
Active
Viewed 911 times
-2
-
2[What have you tried?](http://www.whathaveyoutried.com/) See [ask advice](http://stackoverflow.com/questions/ask-advice), please. – John Conde Jan 25 '13 at 19:44
-
possible duplicate of [Start and stop a timer PHP](http://stackoverflow.com/questions/8310487/start-and-stop-a-timer-php) – Kermit Jan 25 '13 at 19:45
-
for php questions look first to http://php.net/ – Stefan Stawiarski Jan 25 '13 at 19:46
-
@Stefan That's like saying, "for .NET questions look first to msdn.microsoft.com" for any .NET question. Maybe the OP did go to PHP.net first, and a search for "timer between 2 php pages" didn't turn up any results. If only one could downvote a comment. – WhoaItsAFactorial Jan 25 '13 at 20:52
2 Answers
2
Very basic example:
1.php
<?php
session_start();
$_SESSION['start'] = time();
?>
2.php
<?php
session_start();
if(isset($_SESSION['start'])){
$timeSince = time() - $_SESSION['start'];
echo $timeSince . ' seconds since user first loaded 1.php!';
unset($_SESSION['start']); //unset the timer variable.
} else{
//didn't visit 1.php or session has expired. You could force a redirect:
header('Location: 1.php');
exit;
}
?>
It is worth noting that:
- You can't ensure that the user will travel from 1.php to 2.php. They could close their browser or hit the back button. Their session could expire.
- You might want to force a redirect from 2.php back to 1.php if the start session variable isn't present.

Wayne Whitty
- 19,513
- 7
- 44
- 66