PHP program to store 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 making use of the setcookie() function where we will store the date and time value during the first visit of the user. During the second visit, we will just check if the cookie is already set, if yes then display the time stored in the cookie variable.
<center><h2> Last visited time on the web page</h2></center>
//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);
$visit = $_COOKIE['lastVisit'];
echo "Your last visit was - ". $visit;
echo "You've got some stale cookies!";
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 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”.