Cookies: Free PHP & MySQL Tutorial

This tutorial provides a detailed guide on how to add tracking features to your website using PHP and MySQL, including setting cookies, tracking user visits, and sending email with the cookie information.

This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Topics covered in this PHP & MySQL tutorial:

Adding cookies, Tracking the number of visits, Sending an email with the cookie info

Exercise Preview

cookies track visitors example

Exercise Overview

Every website should use analytics to track where visitors come from, etc. That anonymous info is useful, but you can take things a step further if you have forms on your website that people fill out. PHP can find information such as their landing page, how many times they’ve visited, where they came from, etc., and store it in a cookie. Later when that user submits a form, their info is sent along (invisibly to them), offering you more insight into your customers.

SQL Bootcamp: Live & Hands-on, In NYC or Online, Learn From Experts, Free Retake, Small Class Sizes,  1-on-1 Bonus Training. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Initial Setup Before Moving On

If you are doing this exercise in a classroom (or are doing it for a second time) you must complete the following steps before moving on. If you are doing this exercise at home/work for the first time, you can skip this section.

  1. In your browser, go to:

    • Mac: localhost:8888/phpclass/Tracking-Visitors-With-Cookies/setUp.php
    • Windows: localhost/phpclass/Tracking-Visitors-With-Cookies/setUp.php
  2. This will clear your cookies so you have a fresh start for this exercise.

  3. Close the page. You are done!

Coding the Page

  1. In your code editor, open form.php from the Tracking-Visitors-With-Cookies folder in the phpclass folder.

    We’re going to start out by creating several cookies for user tracking. Let’s start by making a counter to track the number of times users have visited our site. We’ll start off the counter at 1. We’ll also give all these cookies a long expiration time because we never know how long it will be from someone’s first visit to the time they submit a form.

    Setting a cookie with PHP is easy; just use the setcookie() function. setcookie() takes the following parameters:

    setcookie(
       'name',
       'value',
       'expire',
       'path',
       'domain',
       'secure',
       'httponly'
    )
    

    For this exercise we only need to worry about the name, value, and expiration. Note also that expiration is a value in seconds and must be a Unix timestamp. We can feed it a Unix timestamp by using the time() function.

  2. Let’s try it out. At the very top of the page, above the doctype, add the following bold code:

    <?php 
        $expiration = 60*60*24*365*3;
        setcookie("visits",1,time()+$expiration);
    ?>
    <!DOCTYPE HTML>
    

    First we set a variable called expiration. Because a cookie’s expiration is valued in seconds, we need to calculate the number of seconds we would like it to last. In this example, we’ll make it last 3 years. We let PHP do the calculation for us, because it is a little easier to update/visualize than writing 94608000 seconds.

    Next, we set a cookie called visits with a value of 1 and make it expire to the value given. When you set a cookie expiration, always use: time()+a number of seconds

  3. To create a cookie that saves the date and time users enter on, we’ll use the date() function. We’d like to output a date that is formatted like so:

    October 21, 2012, 5:15 pm

    The date() function will allow us to format a date in almost any way. Let’s play with it a bit. Add the bold code:

    <?php 
        $expiration = 60*60*24*365*3;
        setcookie("visits",1,time()+$expiration);
        echo date("M j, Y");
        exit();
    ?>
    

    M outputs a three letter version of the month, such as Oct
    j outputs the day of the month without leading zeros, such as 1 or 22
    Y outputs the full four-digit year, such as 2012

    exit() stops the execution of the script. We put this in so we can just focus on this echo for now without seeing the rest of the page.

  4. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/Tracking-Visitors-With-Cookies/form.php
    • Windows: localhost/phpclass/Tracking-Visitors-With-Cookies/form.php

    It should read something like: Aug 23, 2014

  5. Switch back to your code editor.

  6. Now let’s have it format the date a bit differently. Change the echo statement as shown in bold:

    setcookie("visits",1,time()+$expiration);
    echo date("F j, Y, g:i a");
    exit();
    

    Don’t worry so much about what each letter means. You can always look up the date() function in the PHP manual: php.net/manual/en/function.date.php

  7. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/Tracking-Visitors-With-Cookies/form.php
    • Windows: localhost/phpclass/Tracking-Visitors-With-Cookies/form.php

    It should read something like: August 23, 2014, 5:35 pm.

  8. OK, now that we know how we want to format the date, let’s actually add it to a cookie. Switch back to your code editor.

  9. Delete the echo and exit lines and replace them as shown in bold:

    setcookie("visits",1,time()+$expiration);
    setcookie("entryDateTime",date("F j, Y, g:i a"),time()+$expiration);
    
  10. Save the page.

  11. Now let’s write some code on our action page that will display the cookies. Open thankyou.php from the Tracking-Visitors-With-Cookies folder in the phpclass folder.

    This is our pre-made action page. For now we will just display the cookie values.

  12. Around line 17 find the comment code that says Display cookies here.

  13. Delete that comment and add the following bold code:

    <?php 
       echo $_COOKIE['visits'];
       echo '<br>';
       echo $_COOKIE['entryDateTime'];
    ?>
    

    To access a cookie’s value, we use the code: $_COOKIE['myCookieName']
    You should remember this syntax as it is very similar to working with forms and $_POST.

  14. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/Tracking-Visitors-With-Cookies/form.php
    • Windows: localhost/phpclass/Tracking-Visitors-With-Cookies/form.php
  15. Click Signup Now! You don’t have to bother filling out the form. If everything works you’ll be taken to the thank you page and your cookies will be displayed.

    Next we’ll create a cookie that saves the page a visitor enters on. There are many different ways for PHP to get the current page’s URL. We’ve included one popular option that has already been written. While you could write your own method, the nice thing about PHP is that there are so many developers in the world that it is easy to find a robust solution to a common problem.

  16. Open entryURL.php from the Tracking-Visitors-With-Cookies folder in the phpclass folder.

  17. Select all the code on the page.

  18. Copy it.

  19. Close the file.

  20. Switch to form.php.

  21. Just below the $expiration variable and above the first setcookie() function, paste the code:

    $expiration = 60*60*24*365*3;
    
    function currentPageURL() {
       $isHTTPS = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on");
       $port = (isset($_SERVER["SERVER_PORT"]) && ((!$isHTTPS && $_SERVER["SERVER_PORT"] 
       $port = ($port) ? ':'.$_SERVER["SERVER_PORT"] : '';
       $url = ($isHTTPS ? 'https://' : 'http://').$_SERVER["SERVER_NAME"].$port.$_SERVER[
       return $url;
    }
    
    $entryURL = currentPageURL();
    
    setcookie("visits",1,time()+$expiration);
    setcookie("entryDateTime",date("F j, Y, g:i a"),time()+$expiration);
    

    This function uses the $_SERVER variable to display information about the page. It also takes into account whether the page is currently using a secure server (https) or a normal page (http), gets the port (such as :8888) if there is any, and also gets any URL variables. We run the function then save it into the variable $entryURL.

  22. Luckily, finding out the referring URL (the page they came from) is a lot easier. We can just use $_SERVER['HTTP_REFERER']

    However, this will not always be set so we have to check whether it is or not before putting it into a cookie. Below the code you just pasted, add the following bold code:

    $cameFromURL = 'none';
    if ( isset($_SERVER['HTTP_REFERER']) ) {
       $cameFromURL = $_SERVER['HTTP_REFERER'];
    }
    

    This sets a default of none for the variable $cameFromURL in case there is no referrer. If there is a referrer, it will set the variable to the referring page.

  23. Now we can set the entry page and the came from cookies. Below the other setcookie() functions add the following bold code:

    setcookie("visits",1,time()+$expiration);
    setcookie("entryDateTime",date("F j, Y, g:i a"),time()+$expiration);
    setcookie("entryPage",$entryURL,time()+$expiration);
    setcookie("cameFrom",$cameFromURL,time()+$expiration);
    
  24. Save the page and switch to thankyou.php.

  25. Let’s display these new cookies. Under the PHP code you already have add the following bold code:

    echo $_COOKIE['visits'];
    echo '<br>';
    echo $_COOKIE['entryDateTime'];
    echo '<br>';
    echo $_COOKIE['entryPage'];
    echo '<br>';
    echo $_COOKIE['cameFrom'];
    
  26. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/Tracking-Visitors-With-Cookies/form.php
    • Windows: localhost/phpclass/Tracking-Visitors-With-Cookies/form.php
  27. Click Signup Now! (Remember, no need to fill out the form). You’ll see your cookies displayed on the thank you page.

Tracking the Number of Visits

What we’d like to do is increase the visits cookie by 1 every time a user visits the site. We’d also like to only set the entrypage and other cookies the very first time the user visits, not every time.

  1. Switch back to your code editor.

  2. Switch to form.php.

  3. First, let’s make it so that our cookies are only set on the very first visit to the site. We can do this by checking if the visits cookie has been set. If it has NOT been set, then it is the first time they are coming to the site and we can set all our cookies. Just below where you set the $expiration var, wrap the rest of the code in an if statement as shown in bold (don’t forget the closing curly brace!):

    $expiration = 60*60*24*365*3;
    
    if ( !isset($_COOKIE["visits"]) ) {
       function currentPageURL() {
       $isHTTPS = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on");
    

    Code Omitted To Save Space

       setcookie("entryPage",$entryURL,time()+$expiration);
       setcookie("cameFrom",$cameFromURL,time()+$expiration);
    }
    

    This says: “If the visits cookie is NOT set, set all the cookies.”

  4. Save the page.

  5. The visits cookie also needs to increment every time the user visits the site. We can increment the value of v and then resave the cookie using the updated value. Below the if statement you just added, enter the following bold code:

       setcookie("visits",1,time()+$expiration);
       setcookie("entryDateTime",date("F j, Y, g:i a"),time()+$expiration);
       setcookie("entryPage",$entryURL,time()+$expiration);
       setcookie("cameFrom",$cameFromURL,time()+$expiration);
    }
    else {
       $v = $_COOKIE["visits"];
       $v++;
       setcookie("visits",$v,time()+$expiration);
    }
    

    v++ says to take the value of v and increment it by 1. Then we set the cookie equal to that new value.

  6. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/Tracking-Visitors-With-Cookies/form.php
    • Windows: localhost/phpclass/Tracking-Visitors-With-Cookies/form.php
  7. Try it out:

    • Click Signup Now.
    • Click the back button.
    • Reload the page.
    • Click Signup Now.
    • Click the back button.
    • Reload the page.
    • Click Signup Now.
    • Notice the Number of Times Visited just keeps going up and up!
  8. Switch back to your code editor.

  9. The visits cookie should increase every time the user visits the site—but not every time they load a page! We want the visits to increase once per session. (A session ends when the user quits the browser.) This will give a more accurate number for how many times the user has visited your site over time. To fix this we will add a cookie called currentlyHere. We’ll use that to see whether the user is on the site. By not specifying an expiration, it will expire at the end of the session. Add the following bold code:

       setcookie("visits",1,time()+$expiration);
       setcookie("entryDateTime",date("F j, Y, g:i a"),time()+$expiration);
       setcookie("entryPage",$entryURL,time()+$expiration);
       setcookie("cameFrom",$cameFromURL,time()+$expiration);
    }
    else {
       $v = $_COOKIE["visits"];
       $v++;
       setcookie("visits",$v,time()+$expiration);
    }
    setcookie("currentlyHere","true");
    
  10. Now let’s check to see if that currentlyHere cookie exists. If it does not (meaning they haven’t yet visited the page in this session), we will increase the visits. Change the else statement to an elseif as shown in bold:

       setcookie("visits",1,time()+$expiration);
       setcookie("entryDateTime",date("F j, Y, g:i a"),time()+$expiration);
       setcookie("entryPage",$entryURL,time()+$expiration);
       setcookie("cameFrom",$cameFromURL,time()+$expiration);
    }
    elseif ( !isset($_COOKIE["currentlyHere"]) ) {
       $v = $_COOKIE["visits"];
       $v++;
       setcookie("visits",$v,time()+$expiration);
    }
    setcookie("currentlyHere","true");
    

    If the currentlyHere cookie is NOT set, then increase the visits counter by 1. This will only happen at the start of the session. For the rest of the session the currentlyHere cookie will already be set so the counter will not increase.

  11. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/Tracking-Visitors-With-Cookies/form.php
    • Windows: localhost/phpclass/Tracking-Visitors-With-Cookies/form.php
  12. Try it out:

    • Click Signup Now, then click the back button, and Reload a few times.
    • Click Signup Now. Notice the Number of Times Visited doesn’t go up. Good.

Sending an Email with the Cookie Info

We’ve already made a form validation and email script for you, so all we need to do is add the cookies to the mail() function. We need to change the form’s action page from the thank you page to the page that will process our form.

  1. Switch back to your code editor.

  2. Around line 45 change the action as shown in bold:

    <form action="form-action.php" method="post" name="signup" id="signup">
    

    This links to the page form-action.php that we’ve made for you. When the form is successfully completed, it will then attempt to mail out the form. The page that does this is called form-send-email.php.

  3. Save the page.

  4. Open form-send-email.php from the Tracking-Visitors-With-Cookies folder. We have to do a little setting up on this page to make sure it is emailing to the correct address.

  5. On line 2, change the $to variable:

    • Mac:
    $to = "youremail@gmail.com";
    
    • Windows:
    $to = "newuser@localhost";
    

    Now we can actually add the cookies to the email. Let’s think about what we want to do. Obviously we need to add each cookie to the $message variable. But what if the cookies weren’t set (the user might have cookies disabled in their browser)? This would cause an error and the email might not get sent. So we must check whether the cookie is set before we reference it. Rather than repeating the if isset code over and over again we’ll just loop through a list of cookies and see if each one has been set.

  6. Around line 15 find the comment:

    //add cookies here
    
  7. Below that line add:

    $cookies = array('visits','entryDateTime','entryPage','cameFrom');
    

    This is simply an array of all the cookies we want to check for. We can loop through this and save ourselves some coding time.

  8. Below that add:

    $cookies = array('visits','entryDateTime','entryPage','cameFrom');
    foreach ( $cookies as $value ) {
    
    }
    

    This will loop through our array. $value will be the name of each cookie.

  9. Now we want to check if each cookie has been set. Add the following bold code:

    $cookies = array('visits','entryDateTime','entryPage','cameFrom');
    foreach ( $cookies as $value ) {
       if ( isset($_COOKIE[$value]) ) {
    
       }
    }
    
  10. Lastly, we want to append the cookie value to the message. Add the following bold code:

    $cookies = array('visits','entryDateTime','entryPage','cameFrom');
    foreach ( $cookies as $value ) {
       if ( isset($_COOKIE[$value]) ) {
          $message .= "$value: $_COOKIE[$value]\r\n";
       }
    }
    

    Remember the .= will append our string to the $message variable.

  11. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/Tracking-Visitors-With-Cookies/form.php
    • Windows: localhost/phpclass/Tracking-Visitors-With-Cookies/form.php
  12. Fill out and submit the form. Check your email, and you’ll see the cookie values!

  13. Switch back to your code editor.

  14. Close any open files. We’re done for now.

Noble Desktop Publishing Team

The Noble Desktop Publishing Team includes writers, editors, instructors, and industry experts who collaborate to publish up-to-date content on today's top skills and software. From career guides to software tutorials to introductory video courses, Noble aims to produce relevant learning resources for people interested in coding, design, data, marketing, and other in-demand professions.

More articles by Noble Desktop Publishing Team

How to Learn Full-Stack Web Development

Master full-stack web development with hands-on training. Build fully functional websites and applications using HTML, CSS, JavaScript, Python, and web developer tools.

Yelp Facebook LinkedIn YouTube Twitter Instagram