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

Sponsors