Detect a returning user with Browser cookies

There are a few ways to tackle this problem. Let’s take a look at the easiest way to do this.

basically, we will be using the browser’s COOKIES. These are data stored in your browser about your visit on a website. We will use this to our advantage by having the cookie remember actions for us.

We should start by understanding how COOKIES work.

from the image, we assume the user visits a site for the first time. This action requests data from a server somewhere and return it to you. often, but not always, the returned data requests your browser to store specifics from you. this is stored in a cookie. subsequent visits will then read data stored on the cookie. this cookie will already have data stored in it depending on the site you visited.

on the programmer’s point of view. There is a single PHP function for cookies and existing cookies are already available through the $_COOKIE superglobal.

setcookie (string $name, string $value,int $expire = 0)

what setcookie does is creates a cookie under the name of $name with a value of $value, this is the most important part of the method. the 3rd parameter is a unix timestamp of when the cookie will expire(see last paragraph).

We want to detect whenever a user has already visited our site, we can do this with the following code.

if (isset($_COOKIE['visited'])) {
     // cookie set, so it's a returning visitor
     // display page for returning visitors
} else {
     // cookie not set, so let's "tag" this visitor
     setcookie('visited', 1);
     // display page for first time visitors
}

above, we are checking if a cookie with the name “visited” exists, if it does, we show a page for returning users. else, we create a cookie with the name visited and fill it with a value.

we can also apply this to some examples such as showing a pop up for visitors…

if (!isset($_COOKIE['first_time'])) {
      setcookie('first_time', 1);
     // include popup javascript
     // echo the pop up markup
}  else {
    // subsequent visits will hide the popup
}

remember that cookies will be destroyed on certain conditions, this depends on how you set the cookies in the first place. This process is called expiration.
a cookie expires when the browser is closed, at a certain time in the future or a time that has already passed. cookies can also disappear when a user clears
his browsing history or explicitly removes the cookies from the browser.

This entry was posted in Tutorials and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *