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:
First, revisit:
Second revisit:
How to execute this PHP script?
- 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.
- Next, open this PHP file on the browser via the localhost URL. Usually,
http://localhost/LastVisitedTime.php
- Initially, your browser will display “You’ve got some stale cookies!”
- Refresh the web page to find “Your last visited time”.
Explore other programs in PHP here.
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
what is that date(G:i)
This indicates date format
G – 24-hour format of an hour (0 through 23)
i – Minutes with leading zeros (00 to 59)