Cookies and tracking user information

Try this quick little demo, as it shows you the use of cookies. This demo is implemented using JavaScript, but today we'll do talk about cookies and PHP.

What are these things?

Cookies are used to store information on the client side, in the browser. This is data that the webserver wants/needs to know about, but the server will not store the data internally, and HTTP is a state-less protocol. There are quite a few use cases for this. We could store information that records who you are, such as an authentication token. It is also useful for pages that use shopping carts, and in a very common use case, to track you across websites (3rd party cookies) to support ads.

Cookies and PHP

The browser automatically sends the relevant cookies to the server during each request, and the server needs to define new, or modify existing, cookies before any real content is sent back to the user. In fact, cookies must be set before any other content is provided to the user, because the cookie data is sent in the HTTP response header, using the set-cookie key, not in the HTTP response body. Therefore you should set the cookies before any output is produced, including <!DOCTYPE html>.

To set a cookie in PHP, we use the setcookie() function, which takes as parameterrs the name and value for the cookie. We can optionally add an expiration date, path for which the cookie is valid, a domain that the cookie is available to, and other security related parameters. Example:

<?php
  // Grab a value from the form
  $name = $_POST['username'];

  // Set the time to expire to be 86400 seconds from now (aka in 24 hours)
  //expires is given as a Unix timestamp - seconds since epoch 
  $expires = time() + 86400;

  // Set the value.
  setcookie("username", $name, $expires);
?>

To read the cookies received from the browser (not the ones just set using setcookie()), we use the PHP superglobal variable $_COOKIE. Example:

<?php
  // if "Name" exists, do something:
  if (isset($_COOKIE["username"])) {
    $name = $_COOKIE["username"];
    echo "<h1>Hello $name, it is nice to see you again.</h1>";
  }
?>

To delete a cookie, we set the cookie with an expiration date in the past. Example:

<?php
  
  // Set the time to expire in the past 
  $expires = time() - 100;

  // Set the value.
  setcookie("username","", $expires);
?>

Cookies are for everyone

We mentioned that all relevant cookies are sent by the browser to the server.

This allows both JavaScript and PHP to see the same information, and therefore cookies are often used to store information such as the user's first name, or username, an authentication token, or other information that both would need access to. But... remember that cookies are stored on the client side, so they can be manipulated by the user. It would be wiser to store more sensitive information within the server via Sessions.

What did the PHP server see?

Hopefully you have already run the little demo at the top of the lecture. Currently the value of the $_COOKIE supervariable (as seen by the server) is:

Array
(
    [color] => blue
    [animal] => dogs
    [food] => donuts
    [name] => null
)

Practice Problems

  1. Write checkCookie.php: When PHP is called, look for a "sessID" cookie. If present, print "Welcome back" (in HTML). If the cookie doesn’t exist, create a random ID and set the cookie and print "Welcome visitor!". Hint: generate a random number with rand() or random_int(min, max).
  2. Write quote.php: If PHP does not have the "favQuote" cookie, ask the user for favorite quote in a form and save the quote in a cookie identified by "favQuote". For future visits to this page provide the quote.