Things I Can’t Remember – PHP Cookies

This is a simple example of setting a cookie and then using it to display a different splash page each time someone visits the site.

PHP cookies are described at the PHP manual site. Two things to remember about PHP cookies. They must be set before any <html> or <head> tags. And they are read before the page is loaded—so you can’t read the cookie value the first time someone visits your site.

I put the following code into the definitions section of my header. I like to use variables for each of the parameters so that it’s easier to see what I’m changing. $c_name is the name of the cookie. Once it is set it can be accessed from any page on the site. $c_time is expiration time in seconds. In this case 30 days.

$c_path = ”; and $c_domain = ”; mean that this cookie is available everywhere on the site. This cookie doesn’t contain any sensitive information, it’s just a counter, so I don’t need to use https for transmitting and retrieving it. Setting $c_httponly to ‘true’ makes the cookie inaccessible to scripting languages and guards against XSS attacks.

The if statement checks to see if the cookie is already set. If not, it sets the value of $_COOKIE[“spalsh_page”] to 0. Then it uses the parameters to set the cookie.

If there is a cookie already set, then I read the value, add one to it and update the cookie.


$c_name = "splash_page"; 
$c_time = time()+60*60*24*30;
$c_path = '';
$c_domain = '';
$c_secure = 'false';
$c_httponly = 'true';

if( !isset($_COOKIE[$c_name]) ) {
    $_COOKIE[$c_name] = 0;
    setcookie($c_name,0,$c_time, $c_path,$c_domain,$secure, $c_httponly);
} else {
  $c_value = $_COOKIE[$c_name] + 1;
  setcookie($c_name,$c_value,$c_time,$c_path,$c_domain,$secure,$c_httponly);
}

Next I’m going to access the counter and decide which page to display. $splashPage is an array of pages to include. The if statement checks to see if there is a cookie set. Cookie values start at 0 and go on forever. I use the modulus operator % to restrict the value of $whichPage to a value between 0 and $numPages. The require statement just looks in the array and serves up the appropriate page.


$splashPage = array (
      "Deceiving",
      "WellGolly",
      "Combos",
      "SlipIntoView",
      "Checklists",
      "Coartic",
      "Crossword",
      "Artic",
);
$numPages = count($mainPage);

if (isset($_COOKIE['splash_page'])) {
  $whichPage = $_COOKIE['splash_page'] % $numPages;
} else {
  $whichPage = rand(0,$numPages);
}
require_once("./splashPage/$splashPage[$whichPage].inc");

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.