PHP - Write program to use cookies to remember how long ago a visitor first visited the page

Requirements

Write program to use cookies to remember how long ago a visitor first visited the page

Display this value in the page, in minutes and seconds.

Hint

To remember when the user first visited, create a cookie that stores the current time returned by time().

Create the cookie only if it doesn't already exist.

Then, on subsequent page views, subtract the time stored in the cookie from the new value of time(), and then converting the resulting figure into minutes and seconds for display:

Demo

<?php
if (!isset($_COOKIE[" firstVisitTime" ])) {
  setcookie(" firstVisitTime" , time(), time() + 60 * 60 * 24 * 365," /" ," " );
}
?>/*  w w w .  j a va2  s  .  c o m*/
<html>
  <head>
    <title>Remembering the first visit with cookies</title>
  </head>
  <body>
    <h2>Remembering the first visit with cookies</h2>

<?php if (isset($_COOKIE[" firstVisitTime" ])) {
  $elapsedTime = time()-$_COOKIE[" firstVisitTime" ];
  $elapsedTimeMinutes = (int) ($elapsedTime / 60);
  $elapsedTimeSeconds = $elapsedTime % 60;
?>
    <p>Hi there! You first visited this page <?php echo $elapsedTimeMinutes ?>
minute<?php echo $elapsedTimeMinutes != 1 ?" s" :" " ?> and <?php echo
$elapsedTimeSeconds ?> second<?php echo $elapsedTimeSeconds != 1 ?" s" :" " ?>
ago.</p>
<?php } else { ?>
    <p>It's your first visit! Welcome!</p>
<?php } ?>
  </body>
</html>

Result

Related Exercise