Skip to content

PHP program to display the last visited date-time

PHP program to store the current date-time in a cookie and display the Last visited date-time on the web page upon revisiting the same web page. The code is quite simple and small. We are using the setcookie() function where we will store the date and time value during the user’s first visit. During the second visit, we will check if the cookie is already set, if yes then display the time stored in the cookie variable.

LastVisitedTime.php

//LastVisitedTime.php
<html>
<body bgcolor="87ceeb">
<center><h2> Last visited time on the web page</h2></center>
<br>
<?php
//date_default_timezone_set('Asia/Calcutta'); - You can choose any timezone
 
//Calculate 60 days in the future
//seconds * minutes * hours * days + current time
 
$inTwoMonths = 60 * 60 * 24 * 60 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $inTwoMonths);
if(isset($_COOKIE['lastVisit']))
 
{
$visit = $_COOKIE['lastVisit'];
echo "Your last visit was - ". $visit;
}
else
echo "You've got some stale cookies!";
?>
</body>
</html>

Suggested Read:

Results:
Initial state:

PHP code to display last visited time on the web page - initial state

First, revisit:

PHP code to display last visited time on the web page - after refresh

Second revisit:

PHP code to display last visited time on the web page - after second refresh

How to execute this PHP script?

  1. You need to copy the file LastVisitedTime.php to a PHP server. You can use wampserver software which provides an integrated environment to run PHP files along with MySQL database support.
  2. Next, open this PHP file on the browser via the localhost URL. Usually, http://localhost/LastVisitedTime.php
  3. Initially, your browser will display  “You’ve got some stale cookies!”
  4. Refresh the web page to find “Your last visited time”.

Explore other programs in PHP here.

5 thoughts on “PHP program to display the last visited date-time”

  1. blank

    hi thx for information, I have a question, I want to save time in table and use(unserialize) and loop to print the new and the preview visit

Did it help? Would you like to express?