PHP Cookie Problems

by John H
7 minutes

Cookies have been around forever - they are browser based variables that can be set to expire in the future. The variables are helpful for letting a user bounce around from page to page and have some history preserved. Cookies can be used to remember preferences or notify the browser that some event has happened (like a popup has displayed). Cookies are a really valuable tool in web development, but they can be a bit confusing to use in practice. Here are a few tips for using and utilizing Cookies.

Setting a Cookie

To set a cookie in PHP you just need to use the function setcookie(). It takes a few parameters; name, value, expiration, path, secure, and httponly. All parameters aren't necessary so you can set a cookie with as few as two parameters; name and value. You must set a cookie before anything is output to the screen - otherwise you'll get an execution error. The expiration param is set as an integer so using the time() function plus a number of seconds will set the expiration in the future.

<?php
$value = 'something from somewhere';

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);
?>

The manual on setcookie()

Problems with setcookie

You can run into a few problems with setcookie and here are few common problems I've run into.

  • Cookie is not available across the site
  • Cookie is set in function on page but isn't set on another page
  • Cookie is not immediately available
  • Need to update a cookie value

Cookie not available across the site

So the 4th param of the setcookie function is the path. If you leave it out the function will set the cookie to the current path of the page. This can be problematic if the browser is in a subdirectory. For example, if the browser is at domain.com/category/products and a cookie is set then the cookie is only available in the category directory (ex. domain.com/category/otherproducts ), but not outside of that directory (ex not available at domain.com/about ). The solution is to set the path for the cookie to the root of the domain, '/'.

setcookie('cookiename', true, time()+3600, "/"); // sets cookiename to true for one hour across the domain

Cookies set in a function can be funky

Let's say you make a function to set a cookie using a $_GET variable passed through the url. Then instantiate it on all of the pages.

function setMyCookies(){
    setcookie('mycookie', $_GET['var']);
}

setMyCookies();

The problem with this is that it will try to set the Cookie on every page - regardless of the the presence of $_GET['var'] or not. SO it would be set on a page like this domain.com/?var=something, but it would ALSO be set on a page like this domain.com/ - so the cookie goes from existing to not existing over and over.

To fix this behavior you have to check if the Cookie is set first - and if it isn't then set it.

function setMyCookies(){ 
   if (empty($_COOKIE['mycookie'])) { // Cookie mycookie is empty and not set
      //NEED TO SET COOKIE

          if (!empty($_GET['var'])) { // Get variable 'var' is set and not empty
             //SET COOKI
              setcookie('mycookie', $_GET['var']);
          }
    }
}

setMyCookies();

Much of the issue around Cookies is when the cookie is set and when it is available. It is set in the header before any output on the page, but they aren't available until the next page load. This is kind of a bazar behavior, but it is something you have to figure out if you are going to properly use Cookies.

Cookies aren't immediately available

setcookie('mycookie', 'something', time()+3600, '/');
echo $_COOKIE['mycookie'];

// THIS WILL THROW AN ERROR THE FIRST TIME IT LOADS

A cookie can be set on a page, but it won't be available for reference until a page refresh or the next page is displayed. This is because the cookie is set by the server, but it is held by the browser. It is a pain and can cause all kinds of problems, just be sure your program can handle null or unset values - just check for empty or isset before trying to do anything with your brand new COOKIE!

setcookie('mycookie', 'something', time()+3600, '/');
    if (isset($_COOKIE['mycookie'])) {
       echo $_COOKIE['mycookie'];
    } else {
       echo "NO ERRORS!!!";
    }

Updating a Cookies value

setcookie('mycookie', 'something', time()+3600, '/');
    if (isset($_COOKIE['mycookie'])) {
       echo $_COOKIE['mycookie'];
    } else {
       echo "NO ERRORS!!!";
    }

$_COOKIE['mycookie'] = 'something else';

echo $_COOKIE['mycookie'];  // SHOWS 'something else' 

var_dump($_COOKIE); // SHOWS 'something else'

You'd think it would be simple to just set $_COOKIE['cookiename'] = 'something else'; but you can't - well you can but it doesn't work the way you'd expect. First off, you have to understand that a COOKIE is a browser variable. Manipulating a value on the server side is not affecting the browser side. The only way you can set a Cookie and update it is with setcookie();

To test this you will need two pages. I made index.php and index2.php. In index.php setcookie('mycookie', 'something', time()+3600, '/'); then try $_COOKIE['mycookie'] = 'something else'; Now in index2.php do an echo $_COOKIE['mycookie']. You'll notice that on index.php mycookie displays 'something else' but on index2.php it displays 'something'. That's a problem, especially if you are expecting 'mycookie' to be updated with $_COOKIE['mycookie'] = 'something else';

To actually update a cookie you have to use setcookie() and you have to do it before anything is displayed on the page.

setcookie('mycookie', 'something', time()+3600, '/');
setcookie('mycookie', 'something else', time()+3600, '/');
    if (isset($_COOKIE['mycookie'])) {
       echo $_COOKIE['mycookie'];
    } else {
       echo "NO ERRORS!!!";
    }

echo $_COOKIE['mycookie'];  // SHOWS 'something else' But only on refresh

var_dump($_COOKIE); // SHOWS 'something else'

As you can see there is all kinds of situations that can leave your program buggy if you don't know what to expect.

Testing Cookies

To test Cookies in php you can use a few tools. The Cookies array can be var_dump() or print_r() so you can see what is set and available.

var_dump($_COOKIE);

In Chrome

You can also see set cookies in Chrome in the DevTools under the Application Tab. This is handy because you can also delete page cookies there too.

Related Articles

PHP and Class Variables

Pass a variable into a class through the construct($variable) function Variables set in the...

John H John H
~1 minute

Pulling Facebook Page updates

https://www.codeofaninja.com/2014/10/display-facebook-page-feed-on-wordpress-or-website.html...

John H John H
~1 minute

HTML to PDF Resources

I'm looking for some options to convert html to PDF.  There are a few reasons to do this.  The...

John H John H
~1 minute