Baking Cookies in PHP

Have you ever wondered that in spite of HTTP being a stateless protocol, when you log in to a website and buy stuff and checkout how the server can identify you uniquely? You might wonder if HTTP is stateless but your state is maintained through your interactions, isn’t this a contradiction? Welcome to world of cookies (not the ones which we can eat, btw :)), one the of primary ways to maintain user state and interaction between the web browser and the web server.

Cookies are tid-bits of information stored by the browser on a user’s computer. The information stored in the cookie is used to uniquely identify a user and this information is sent to server with each request so server can make use of it. Cookies can store a variety of data, such as your name, the date of your last visit, shopping cart contents, etc. Cookies stored by one website can not be accessed by other websites, which makes cookies relatively safe to store personal information. Still, it is a good idea not to store sensitive information in them, like passwords and credit card information.

The Lifecycle of a Cookie

Here’s what the lifecycle of a PHP cookie looks like, from baking to eating:

There are no cookies when the browser connects to particular server for first time. When the request is made to the PHP script, the script makes a call to the setcookie() function. This causes a Set-Cookie HTTP header to be sent in the response that contains the name and value of the cookie to be set.

When the browser receives the response, it stores the value of the Set-Cookie header as a cookie locally. When multiple requests are made to server afterwards, the browser includes a Cookie header containing the name and value of the cookie. PHP intercepts it and creates an entry in the $_COOKIE array with name and value of the cookie.

Baking PHP Cookies

PHP provides access to cookies through a function named setcookie() and the superglobal array $_COOKIE. setcookie() stores data in cookies, and $_COOKIE retrieves values from cookies.

Setting Cookies

The function setcookie() is used to set a value and the optional expiration date of a cookie. The syntax for the function is:

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

The meaning of each parameter and whether it is required or optional is listed in the following table adapted from one appearing on W3Schools:

Let’s look at an example of setting a cookie in PHP code.

<?php
$firstcookie = "my first cookie";
$expiry = time() + (60 * 60 * 8);

// send a cookie that expires in 8 hours
setcookie("FirstCookie", $firstcookie, $expiry);

The code sets the cookie value in the variable $firstcookie and the expiration date in variable the $expiry. The cookie name is set as “FirstCookie” in the call to the function setcookie(). The cookie name can be anything you wish.

Note the cookie will expire in 8 hours (seconds × minutes × hours beyond the current time). But what if you want your cookie to be deleted immediately or once its information is retrieved by the browser? You can set the expiration date to a time in the past. For example, you can set $expiry as time()-3600.

Cookies by default are set only for the current directory and its descendants. The fourth parameter path restricts access to the cookies to a given path on your server. For example, if the cookie is set with “/test/” directory, then it will be available only to scripts in the test directory and its subdirectories. If you want cookie to be set for root directory, then “/” should be used as path parameter, as in this example:

<?php
setcookie("FirstCookie", $firstcookie, $expiry, "/");

The fifth parameter domain restricts access to the cookie to a given domain. For example, if you want a cookie to be accessed from two different web servers like www.trial.com and support.trial.com then set the domain parameter as .trial.com. Doing this will make cookie available to both servers.

<?php
setcookie("FirstCookie", $firstcookie, $expiry, "/", ".trial.com");

Cookies are sent to the browser using header fields in the HTTP protocol. Because of this, it’s necessary to set cookies before sending a single line of HTML or any other output to user. Cookies will not be set if any output is sent. In this case, the setcookie() function will return false and PHP will produce an error message.

Retrieving and Updating Cookies

Retrieving cookies is fairly simple in PHP. The global array $_COOKIE is used to retrieve the cookie value for subsequent page requests. For example, if you want to display the number of times a user has visited, then the following code should do the trick:

<?php
$visits = 1;
if (isset($_COOKIE["visits"])) {
    $visits = (int)$_COOKIE["visits"];
}
setcookie("visits", $visits + 1, time() + (60 * 60 * 24 * 30));
echo "You have visited this page $visits time(s).";

A cookie is automatically deleted by web browser once its expiration date passes. So, setting the expiration parameter of setcookie() function to some arbitrary time in the past deletes the cookie. setcookie() uses same domainname, pathname, and cookiename as specified when the cookie was created; only the value and expire parameter has to change. Here the value parameter is set to null and the expire parameter is set to some arbitrary time in past in this example.

<?php
$expiry = time() - 60;
setcookie("FirstCookie", $firstcookie, $expiry, "/", ".trial.com");

Final Crumbs

There are cases when a user may wish to turn off cookies in the browser for privacy reasons. Therefore, before using cookies, it is recommended to always first test whether the user has cookies enabled or not in browser. You can do this by setting a cookie then redirecting to next page with flag in URL and checking if the cookie was received back. If not, then display a message to user suggesting they enable cookies.

Disabling cookies on a site that requires cookies thus disables the site’s functionality. In this case, we need to find other ways to maintain state. One alternative is to use PHP sessions and append a sessionID to the URL, but beware this approach can lead to social attacks.

When using cookies, there are a few things you should keep in mind:

  • A server can define multiple cookies with different names, but browsers limit the number of cookies per server (the count varies between browsers, but is generally around 20).
  • The maximum size of any cookie is 4KB.
  • Although you set an expiration on the cookie, a user can delete cookies at any time.
  • Cookies can only be accessed by the browser that set them (Firefox and IE don’t share them).
  • A user can turn cookies off in their browser.
  • Cookies must be set before any other output is sent from the PHP script or else you will receive an error.

That’s all for cookies. You should now be able to use cookies in your PHP applications, so start baking and let me know how your cookies taste!

Image via Fotolia

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Lucas Rolff

    Also it would be good to mention, the really ‘awesome’ cookie law in EU.

    • http://zaemis.blogspot.com Timothy Boronczyk

      In hindsight, perhaps a brief discussion of the EU law would have been a good add. Thanks for the suggestion! For those interested in learning more, I recommend starting with theeucookielaw.com.

  • http://www.rommelxcastro.com Rommel

    useful information (:

  • Mark

    Firstly no mention of the EU cookie law? Secondly using none OOP methods? Thirdly using information from WC3 when it is well known to be poor quality? Really is this a PHP master site, why are you letting the quality slide to this mush?

  • http://zaemis.blogspot.com Timothy Boronczyk

    As far as I know, there is no native OOP cookie extension. One can work with cookies in PHP easily thanks to the built-in setcookie() function and $_COOKIE superglobal; it’s a trivial exercise to write your own OOP wrapper around them if you prefer such an API.

    I think you meant W3Schools in your comment, not WC3 (World Wide Web Consortium). I re-read the article and I didn’t see any references to either site, so I don’t understand your concern on this point.

    I’m sorry you disapprove of this article, Mark. It was intended as a gentle introduction to working with cookies and to show how to set them in PHP, and as such was categorized as a beginner article. You appear to be well on your way to becoming a PHP Master, so maybe you would find our articles categorized in the other skill-levels more interesting.

    Implement Two-Way SMS with PHP – Intermediate

    Rest – Can You Do More than Spell It? – Advanced

    Reusing Implementation – a Walk-through of Inheritance, Composition, and Delegation – Expert

    • Alex F

      I believe that Mark’s W3 comment may be referring to the table. It is EXTREMELY similar to the the table used at http://www.w3schools.com/php/func_http_setcookie.asp
      I thought of that as soon as I saw it as well. It is great to offer tutorials for the beginners, but the author should make sure to use original content or give credit when using others’ work (not saying that is necessarily the case here).

      • http://zaemis.blogspot.com Timothy Boronczyk

        Hrm, I see the concern now. You are right, it is VERY similar. I wasn’t aware when I reviewed the article. I’ve added proper attribution and I apologize for that oversight!

        • mark

          Its not your fault Tim its down to the author to disclose any sources they have copied/used, you can’t know everything on the web :) but please don’t use W3schools as an information source we should do all we can to discourage people from using that misinformed garbage

        • http://student Tina Woodbury

          I am trying to learn how to count the number of times I refresh or visit the page using setcookie() function it is not counting and wondering if anyone knows where I could go for the information that I need, everywhere I have been is already telling me what I already know plus the book I have tells me the exact same thing but can’t find anywhere to help me know how to count thank you for your time, and I thought the article was very informative if I didn’t have a book

  • Les

    @Tim
    Ignore Mark as he is just a troll. If this person was a PHP developer of any note he’d already know there was no OO implementation for COOKIE with PHP.

    Yes, I was expecting more myself but I do appreciate this article is aimed towards the beginner so it doesn’t bother me as such and… it’s always a good idea for us more experienced developers to get back to basics now and again.

    • mark

      No Les nothing troll about it. There is absolutely nothing stopping anyone from setting a cookie using classes in an OO manner other than sheer laziness or unbelievable arrogance not sure which one this is. This site is labelled PHPmaster and promotes procedural code used in the 90’s, PHP already has enough bad rep for promoting old outdated (and most of the time un-safe) methods on blogs and forums the last thing we need is another site doing the same. Ok this article is aimed at ‘beginners’ but as a community of more experienced devs (as I would guess authors here should be) still need to be teaching best practices otherwise these ‘beginners’ will simply think that this is the ‘correct way’ and continue to drag PHP backwards to its early days.

      This is not a general comment at PHPMaster as there are some very good articles on here from authors who clearly know what they are talking about and using up to date methods and best practices but sadly this article falls way short.

      • Suri

        I was expecting more on cookies too, but as this is for beginners, there is nothing to complain. Perhaps Mark can present us with some thing more than this on Cookies.

  • http://harikt.com/blog Hari K T

    Critics are good to learn and improve ourselves. So let’s hear everyone. We are here to share what we know :).
    So this is for a person who is just starting with PHP. He do want to know what exactly is going under the hood.

    If you are interested in an OOP based implementation have a look into Aura.Http . Probably you may love https://github.com/auraphp/Aura.Http . Let us know your thoughts on it.

  • http://blogverize.blogspot.com Nimsrules

    Stepping into core PHP development after using WordPress, this was the best tutorial I could have landed upon to learn about cookies. Thank you for the simpler explanation Sneha.

  • grizzley

    As a relative beginner still strugling with the oop concepts I found this really useful and helpful; explained really simply without added complications. Lets get the basics then we’ll progress to oop!

  • Rahul

    You always prove that, you have the best PHP codes to implement.

  • http://heera.it Sheikh Heera

    Nice tutorial. It’s categorized under beginner and it’s really a good tutorial for beginners and to be honest it helped me too because for a long time I’m not using native php (depended on frameworks) and almost forgot things like this but it really helped me. Keep writing. Thanks !

  • Mosi

    Good article for beginners :)
    We have categories for beginner, intermediate, advanced… that’s why such posts should be found on phpmaster.

  • luis

    im starting to learn php and im fairly new, oop still puzzles me so the fact that this is written in in a procedural way makes it easy to understand

  • Good

    clean and simple nice for beginners i don’t know why some guys
    given negative comments :(