The anatomy of a PHP cookie
What is a cookie?
A cookie is a text file that is sent from the server and is stored in the browser’s cache. Cookies can enhance the usability of your application by either setting predefined variables within the application or gathering information entered by the user during a site visit.
For example if you visit Amazon when browse the site and click on specific products then return to that site a few days later you will often find that your previous browsing history will be displayed if cookie exists.
A cookie is not…
A cookie is not a program. It contains no logic – only key value pairs. It cannot independently do anything to your application or browser it is simply a repository of text based information that is sent from or fed back to a server.
setcookie(name[, value[, expiryTime[, path[, domain[, secure[, httpOnly]]]]]]); setcookie("name", "value", NULL, NULL, NULL, TRUE, NULL); setcookie('visits', $numVisits, time() + 3600 * 24 * 365);
A practical example
Controller Code
if (!isset($_COOKIE['visit_num'])) { $_COOKIE['visit_num'] = 0; $_COOKIE['username'] = ''; } $visits = $_COOKIE['visit_num'] + 1; $username = $_COOKIE['username'] = "Toby"; setcookie('visits', $visits, time() + 3600 * 24 * 365); setcookie('username', $username, time() + 3600 * 24 * 365); include 'main_dashboard.php';
What’s happening?
We are sending a cookie which has expiry of one year. The visits are set to zero but each time the user logs in the visit_num total is set to plus 1. We ale define another cookie to set the username.
View code (main_dashboard.php)
<body> <p> <?php if ($visits > 1) { echo "Hello $username."; echo "This is visit number $visits."; } else { // First visit echo 'Welcome to the store! Click here for a tour!'; } ?> </p>
What’s happening?
The Cookie is loaded into memory from the cache we then check the total of the $visits total. If it is equal to 1 we know this must be their first time and so we display a welcome message.
Cookie parameters
Parameter | Description |
---|---|
name |
Name of the cookie to be sent (variable name) |
value |
This could be a single value or an array |
expiryTime |
If not set the cookie will expire after the browser session |
path |
This can be used to restrict what parts of the application can access the cookie – for example /admin/ (Note the use of the trailing ‘/’. This prevents users inputting adminfake) |
domain |
If you set this ‘.example.com’ this is helpful if you are running multiple domains such as support.mydomain.com. Note the leading ‘.’ This prevents users fake domains from accessing your cookies |
secure |
Setting secure to ‘1’ will mean only URLs with HTTPS can use the cookie |
httpOnly |
When setting this parameter to ‘1’ it prevents JavaScript from seeing the cookie. This can be helpful in preventing malicious JS from being injected into your application and thus compromising your site |
As a rule of thumb only use cookies to store non-essential information
Some considerations when using cookies:
- Browsers can set limits on the amount of cookies that a web application can set – this can vary depending on the browser you are using. Here is a really useful tool to find out how many cookies per site a browser can allow: http://browsercookielimits.squawky.net/
- Cookies should not be used to store sensitive user information such as passwords
- Be aware that if you exceed the cookie limit set by the browser previous cookies will be removed
- Cookies are only good for storing small amounts of information (roughly 5mb per browser) – however given that it is text based data 5mb is still quite a lot!
Are cookies secure?
Inherently yes because Cookies exist on the client side and not on the server and also they only relate to the specific site that they are tied to so any information cannot somehow be redistributed. It also really depends on the type of information that is being stored within it.
As a rule of thumb only use cookies to store non-essential information such as:
- General user settings – font-size, positioning of elements etc
- Last five products browsed
- Basic user details such as first name to provide a more localised personal experience
But what if I have no choice but to store sensitive information?
If storing sensitive information is unavoidable in your cookie one possible alternative is to encrypt the data such as using salting or hashing data.
When to use Cookies
Cookies are really useful for storing non-sensitive information that is not memory intensive and can enhance usability for the user. A big win with Cookies is their off-line capabilities when using third party cookies which can be accessed by JavaScript. Because the cookie is stored on the client side the user does not need to be logged in to your server to make use of the information.
For example form information such as name and address, latest products that relate to the users interests could also be stored in a cookie.
What are Third Party Cookies?
Third party cookies are often used to track user information such as products viewed etc and to track general browsing activity. This data is then shared across the different sites you visit. For example if you are wondering how Facebook knows about that book you viewed on Amazon it is because it or a partner provider is accessing a third party cookie that has stored that information which is being made available to all sites that require it.
What are the alternatives to cookies?
HTML5 Local Storage and HTML5 Caching provide viable alternatives to using cookies. However it is important to consider who needs the data, the client or the server? Local storage can only be accessed by JavaScript and not server side languages such as PHP.
Another consideration to bear in mind is that local storage does not allow you to set an expiration date and data is only changed if updated by the JS.
To recap
In this post we have explored the structure of a PHP Cookie and explained the settings within. We also identified when we would use a cookie and discussed the type of data and scenarios where cookies would be best suited.