Baking Cookies in PHP

Share this article

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

Frequently Asked Questions about Baking Cookies in PHP

How can I set a cookie in PHP?

Setting a cookie in PHP is quite straightforward. You can use the setcookie() function, which allows you to create a cookie. The function requires at least two parameters: the name of the cookie and its value. Here’s a simple example:

setcookie("test_cookie", "test_value");

In this example, “test_cookie” is the name of the cookie and “test_value” is the value assigned to it. This cookie will expire when the browsing session ends. If you want to set an expiration date, you can add a third parameter to the function, which represents the expiration time in seconds.

How can I retrieve a cookie value in PHP?

Once a cookie is set, you can retrieve its value using the $_COOKIE superglobal array. The array holds all the cookies that are currently accessible. To retrieve a cookie value, you simply need to refer to the array element that corresponds to the cookie name. Here’s an example:

echo $_COOKIE["test_cookie"];

This will output the value of the “test_cookie” cookie, which is “test_value” in our previous example.

How can I delete a cookie in PHP?

To delete a cookie in PHP, you can use the setcookie() function again, but this time you need to set the expiration date to a time in the past. Here’s an example:

setcookie("test_cookie", "", time() - 3600);

In this example, the “test_cookie” cookie will be deleted because its expiration time is set to one hour in the past.

What is the scope of a cookie in PHP?

By default, a cookie is accessible on all pages within the domain where it was set. However, you can limit the scope of a cookie by setting its path when you create it. For example, if you want a cookie to be accessible only within a specific directory, you can do so like this:

setcookie("test_cookie", "test_value", time() + 3600, "/my_directory/");

In this example, the “test_cookie” cookie will be accessible only within the “/my_directory/” directory.

Can I store arrays or objects in a cookie?

Yes, you can store arrays or objects in a cookie, but you need to serialize them first because a cookie can only store string data. Here’s an example:

$array = array("name" => "John", "age" => 30);
setcookie("test_cookie", serialize($array));

To retrieve the array, you need to unserialize the cookie value:

$array = unserialize($_COOKIE["test_cookie"]);

Are cookies secure?

Cookies are not inherently secure because they can be intercepted and modified by attackers. However, you can make them more secure by using the secure and httponly flags when you set them. The secure flag ensures that the cookie is sent only over secure (HTTPS) connections, while the httponly flag prevents the cookie from being accessed through JavaScript.

What is the maximum size of a cookie?

The maximum size of a cookie is 4KB, including the name, value, and all attributes. If you need to store more data, you should consider using sessions or a database.

What is the difference between a session and a cookie?

A session is a way to store information on the server side, while a cookie is a way to store information on the client side. Sessions are generally more secure and can hold more data than cookies, but they require more server resources.

Can I set a cookie without a value?

Yes, you can set a cookie without a value. In this case, the cookie acts like a flag. Here’s an example:

setcookie("test_cookie");

Can I use cookies to track user activity?

Yes, you can use cookies to track user activity on your website. However, you should be aware of privacy laws and regulations, such as the General Data Protection Regulation (GDPR) in the European Union, which require you to obtain user consent before tracking their activity.

Sneha HedaSneha Heda
View Author

Sneha Heda has experience with Perl, PHP, Linux, MySQL, and MSSQL. She worked at Cognizant Technology Solutions with multinational clients, but the views presented here are not related to her job. She likes cooking and traveling.

Beginner
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week