Cookies Tutorial

Web programming topics
Post Reply
User avatar
Shane
Captain
Captain
Posts: 226
Joined: Sun Jul 19, 2009 9:59 pm
Location: Jönköping, Sweden

Cookies Tutorial

Post by Shane » Wed Sep 30, 2009 3:49 am

Part 1 - Introduction to Cookies

Introduction
Cookies are a technology which can be easily and simply used by a Webmaster to achieve a great many very useful tasks when creating websites. Although cookies are well known to users, many people are not really sure what they are used for, and a large amount of webmasters don't realise the possibilities open to them when they use cookies. Others have been put off, thinking that they must be difficult to use, but in reality, cookies can be set and used by a simple command in most scripting languages. In this tutorial I'll cover setting and using cookies in PHP, JavaScript and ASP, as well as giving some basic information on how cookies can be used.

What Is A Cookie?
Apart from being a type of biscuit, a cookie is also a very useful piece of technology for use on the web. One of the problems which many websites need to overcome is that there is no way of directly finding out who is on a website. Although many details about the user (such as their browser, IP address and operating system) are available, the use of dynamic IP addresses (which change every time the user logs on) and IP address sharing (so that many people share the same IP) mean that there is no reliable way of recognising a particular user when they re-visit a website.

Cookies overcome this problem. They basically give the website owner the opportunity to store a little piece of information on a user's computer which they can then retrieve at a later date. Cookies are just tiny text files (only up to 4Kb in size) and a website can write them to the user's computer via the web browser. The same website can then request the cookie from the user and, if it exists, the value stored will be reported back to the website. The cookie can persist on the user's computer, staying there if the browser is closed, the computer is switched off and if the internet connection is changed.

What Use Is A Cookie?
So why would anyone want to store 4000 characters of text on a user's computer? It isn't enough to put anything really worthwhile on there! The power of the cookie, though, is to recognise a site visitor over and over again. To give just a few uses of cookies:
  • Many portals and search engines use them to provide customized pages and results to their users, allowing such features as 'My Yahoo' etc.
  • Many websites use cookies to log their users in automatically. By storing a few pieces of user information they can automatically authenticate the user's details and use them to save the user time when they log in>/li>
  • Visitor tracking and statistics systems often use them to track visitors. By assigning the visitor a cookie, they will not be counted more than once, so accurate unique visitor statistics can be obtained. Also, if a user has a unique cookie the system can 'follow' them through a website, showing the webmaster exactly where the visitor has been, and in what order.

Using Cookies
A cookie is a very basic data file. It has a name and a value and also stores the address of websites which are allowed to access it and an expiry time. Basically, a website will set a cookie and give it a name and value. This name is used by the website to refer to it, and no other website can access the cookie, even if they know it's name. The name should be unique to the website, but it doesn't matter if it clashes with the name of a cookie from another website.

The cookie (as mentioned before) can only store up to 4000 characters of data. This is enough to store lots of information about a user so if, for example, you wanted to store the user preferences for a search engine (much like Google does), you could simply list the preferences in the cookie. If you wanted to store more data, you would have to store a unique ID in the cookie, which matched up with a database record, and you could then access the user's data this way.

To retrieve data, the website simply has to request if the user has a cookie with a particular name. If the user does, the value is returned to the script and it can be dealt with however the website owner chooses (for example a name stored in a cookie could be returned, a user ID could be loaded from a database, or a record could be made of a user visiting a site).

Every cookie is assigned an expiry date and time. It is up to the website owner to decide how long the cookie should exist for. Many owners may just choose to set the cookie for an hour, meaning it is only available for the user's single session. This is common in visitor tracking. Other cookies could be set for much longer. Maybe a week or a month (often used for affiliate program tracking) or even several years (often used for user preferences).

Cookie Security
Despite much worrying in the news a few years ago, cookies pose no real danger to users. Unless they are really worried about themselves being recognised by a website, they are harmless. The browser actually writes and reads cookies from the computer when requested to by a website, so a malicious website cannot damage the computer.

For webmasters, there are some security concerns. When the cookie is set, the domain(s) which can access it are set. Usually this is just the website who set the cookie. This makes them relatively secure, as you can be sure that your competitor cannot load your cookie from one of your visitors' computers (they cannot even find out if it exists).

One major security problem with cookies, though, is that they can easily be read by anyone using the computer. They are just a simple text file, so you should not under any circumstances store passwords in cookies. A common way to log people in automatically is to store an encrypted version of their password, which can then be matched with an encrypted version on the server. Another method is to store a unique ID and a unique validation number on the user's system. This is then referenced in a database to the user's account. This way, no actual details are stored and a malicious user cannot simply guess users' IDs (as there is the validation number).

Part 2 - PHP and Cookies

Introduction
This section of the tutorial covers the use of the PHP scripting language to set and read cookies. Cookies in PHP are not difficult to implement, and there are only two commands that need to be used with them. PHP makes it easy to set and read cookies and provides all the features needed to give their details.

Setting a Basic Cookie
The PHP function for setting cookies is called:

Code: Select all

setcookie() 
It is a PHP function which can be used without returning a value (for example you can simply execute a setcookie()) command, or you can take the return value and use it. The setcookie() function returns a boolean (true or false) value depending on whether it is successful. So you could execute:

Code: Select all

if(setcookie())
{
echo "Cookie set";
}
else
{
echo "Cookie not set";
} 
For the purposes of this tutorial, though, we will not be using the return value, instead simply setting the cookie.

The most basic information for a cookie is it's name and it's value. The name of the cookie must be something which you can refer to it later as. You don't need to worry about it clashing with other sites as cookie names are site specific but you should try and use a descriptive and unique name for your cookies.

For this first example, assume that you have used PHP to load the user's name into the variable $name and want to greet the user in the future by their name. You would need to create a cookie which stores their name as follows:

Code: Select all

setcookie("UsersName",$name); 
This creates the most basic of cookies, storing the user's name in a cookie called 'UsersName'. By setting cookies like this, you don't set any specific options, so by default the cookie will be available to the domain in which it was set (e.g. yoursite.com) and will be deleted when the user closes their browser.

Reading Cookie Values
PHP makes it extremely simple to read the value of a cookie. In PHP, reading form values are achieved using $_GET and $_POST. PHP has a similar global variable for cookies:

Code: Select all

$_COOKIE['CookieName']; 
This variable contains the value of the cookie with name 'CookieName'. So on your website, if you wanted to display the name of the user, you could simply use the following:

Code: Select all

echo "Hello, ".$_COOKIE['UsersName']."! Welcome back!"; 
Of course, the user may not already have the cookie, so you should use the PHP function isset. This returns true if a variable has been set and false if not. Using this, your site could do the following:

Code: Select all

if(isset($_COOKIE['UsersName'])
{
echo "Hello, ".$_COOKIE['UsersName']."! Welcome back!";
}
else
{
setcookie("UsersName",$name);
} 
Cookie Settings
Although the code I have given you allows you to set a simple cookie on the user's computer, it isn't very powerful because, for example, it is lost when the browser closes. One of the most powerful features of cookies is the ability to set and expiry date for the cookie. The cookie will remain on the users computer until the expiry date, then will automatically delete itself.

To set a cookie with an expiry date, use:

Code: Select all

setcookie("UsersName", $name, time()+3600); 
This code takes the current time (using time()) and then adds 3600 seconds to it, and uses this value to set as the expiry time for the cookie. Basically this means that the cookie will remain on the user's computer for an hour (it expires 3600 seconds (1 hour) from the current time). For one week (for example) you would set the cookie as:

Code: Select all

setcookie("UsersName", $name, time()+604800); 
There are three other options which can be used when setting cookies. Firstly the path. This refers to where in the domain you are able to access the cookie in future. By default this is the current directory (so if you set the cookie at the page: www.mysite.com/scripts/setcookie.php, it would only be available to scripts in the scripts directory and below). You can set this to any part of your site, though, which can be useful in some situations.

A second setting you can change is the domain. By default, a cookie is only available in the domain you set it in, for example if you set the cookie on www.mysite.com you can only ever access it from www.mysite.com (and not mail.mysite.com etc.). The most common need to change this setting is to allow the cookie to be viewed across all subdomains of a site. This can be done by setting the domain to .yoursite.com (with both .s). By doing this anything.yoursite.com is accepted, not just www.yoursite.com.

Finally, a cookie has the option to be set as a secure cookie. If this is turned on, the cookie will only ever be surrendered to the site over a secure connection, not an insecure one.

The following code shows the implementation of a cookie with all settings specified:

Code: Select all

setcookie("UsersName", $name, time()+3600, "/", ".mysite.com", 1); 
The cookie set here, is called 'UsersName' and again stores the value $name. It will expire an hour from the current time. It is available in all directories of the site (/ is the root directory). It is available across any subdomain of the site mysite.com as '.mysite.com' has been given as the domain. The final 1 means that this is a secure cookie, and can only be transmitted over a secure connection. This would be 0 for a standard (non-secure) cookie.

Deleting Cookies
There are occasions on which you may wish to delete a cookie from a user's computer. This could be if, for example, you want to log the user out of a system (perhaps they are on a public computer). Deleting a cookie is quite simple to do because all you have to do is to set the expiry time in the past. By doing this, the cookie will be automatically deleted as soon as it is created, and will remove any data that already exists there. The simplest way is using:

Code: Select all

setcookie("UsersName", "", time()-3600); 
This sets the expiry time in the past so it should be deleted immediately. There is also no information stored in the cookie.

There is a known problem with this, though. Although it works in most cases, there can be problems if a user's time zone is set wrongly. The safest way to completely delete a cookie is to use the following:

Code: Select all

setcookie("UsersName", "", mktime(12,0,0,1, 1, 1990)); 
The mktime() function is a PHP function for setting up a time specified. The time specified here is in the year 1990, so even a badly configured computer should still delete the cookie immediately.
Post Reply

Return to “Web programming”