Writing a 'You Last Visited' PHP Script

01
of 04

The Full Code

More information about how this script works, and what each section does is on the following pages.

02
of 04

Setting and Retrieving the Cookie

<?php if(isset($_COOKIE['AboutVisit'])) 
{
$last = $_COOKIE['AboutVisit']; }

In the first part of the code, we check to see if a cookie is set. If our cookie (named AboutVisit) is set, we retrieve it and assign it to the variable $last. It is important that we do this before we set the cookie, otherwise, we will overwrite the old date before we ever see it.

$year = 31536000 + time() ; 
//this adds one year to the current time, for the cookie expiration
setcookie(AboutVisit, time (), $year) ;

Next, we create a variable called $ year. This adds one year to the current date, by adding 31,536,000 seconds (60 seconds * 60 minutes * 24 hours * 365 days.) We use this as the new cookie's expiration date. We then set our new cookie to be the current time. We must be sure when we set a cookie that it is the first thing sent to the browser or it will not work. Any text, HTML, or even a page title will make it not work. These things should all follow the cookie.​

03
of 04

Welcome Back

This code first checks if $last is set. If you remember from the last step, $last is the time the visitor was last at the site. If they have visited before it then runs through two options. If the visitor has visited within the last day, it simply thanks them for visiting the site. If, however, the visitor visited over 1 day (86,400 seconds) ago, the message welcomes them back and reminds them of when they last visited.

04
of 04

New Users

If $last did not exist, then this code executes. It simply welcomes a first time user to the site. They now have a cookie set in their browser so they will not get this message again.

The top part of the script, that retrieves and sets the cookie, needs to be placed at the very top of a page to work. The rest of this script can run anywhere on your site that you want to welcome a user.