Digital Development
Web Design

So you're on the internet everyday and you hear about cookies all of the time, but what exactly are they?...and why on earth are they called cookies? If they're not the yummy, edible kind why should I spend my precious time reading about them when I could be getting chocolate chips between my teeth? Brush the tech crumbs aside and you'll see that it all comes down to how PHP, a server-side scripting language, makes your web browsing experience more pleasant. When browsing, you're making use of the HTTP transfer protocol to view different web pages, however, every time you switch to a new page you're losing any information you may have entered...continually entering in usernames, passwords, registration forms is no fun for anyone, agreed? PHP's cookies and sessions allow you to move about freely without losing any entered information, saving you the job of repeating the entry process, i.e these tools prevent your data from being lost.

Cookies Explained

Cookies are small pieces of information placed on your computer by the websites you visit. This allows sites to retrieve the stored information, such as your viewing preferences, or your number of page-views, the next time you access the site. Some sites will set cookies to track visitor usage and habits and people sometimes consider that an invasion of privacy, but typically its not a problem...a bit more on silly lawyers later....for the moment here's some details on the PHP cookie:

  • Stored on the client computer and are thus decentralized.
  • Can be set to expire after a period of time from seconds to years.
  • Browser can store approx 20-50 cookies, depending on the browser, of 4KB each, per domain.
  • If the client disables cookies no information will be stored, i.e. don't depend on them for your website to function.
  • As they reside on the client system the client can edit these files.
  • Information set in the cookie is not available until the page is reloaded.
  • They're not very secure. Can easily modify contents to insert data that could potentially break your application or compromise security. Thus they're useful only for general information and nothing requiring any level of privacy
  • As all the cookie data for a Web site is sent every time the browser requests a URL on the server, the browser needs to upload this data each time the user views a page and can slow things down if there are a lot of cookies (imagine 50 cookies of 4KB each!).

Creating Cookies

Cookies are created through PHP using setcookie(). Cookies must be called before sending any output to the browser as setcookie() needs to send the Set-Cookie: HTTP header. Should you send information to the browser first, the HTTP header is sent before cookies are called and thus all cookies are ignored. The only required field to be included in setcookie() is the cookie name and its associated value, e.g. setcookie( "pageviews", 5). The name of the cookie is automatically assigned to a variable of the same name and stored in the superglobal $_COOKIE array. For example, if a cookie was sent with the name "user", a variable is automatically created called $user, containing the cookie value. There's a number of very useful optional parameters which can also be included in setcookie(), here's an example with an explanation of the optional parameters:

setcookie("pageviews", 3, 0, "/", "", false, true)

name - pageviews
value - 3
expires - 0, i.e. the cookie will last as long as the browser is running, and is automatically deleted when the browser exits.
path - The path the browser should send the cookie back to. It's generally a good idea so specify a path. Use a value of "/" if you want the cookie to be available to all URLs in your Web site.
domain - If empty, the browser only sends a cookie back to the exact computer that sent it. If you set domain to the browser will send the cookie back to all URLs within this domain, including URLs beginning with,, or http://
secure - This field, if present, indicates that the cookie should be sent only if the browser has made a secure (https) connection with the server. Omit this field, or set to false, if you're working with standard (http) connections.
HttpOnly - This field, if present, tells the browser that it should make the cookie data accessible only to scripts that run on the Web server (that is, via HTTP). Attempts to
access the cookie via JavaScript within the Web page are rejected. This can help to reduce your application's vulnerability to cross-site scripting (XSS) attacks.

Raw Cookies

The value portion of the cookie will automatically be URL encoded when used to load a page. If you don't want this, you can use setrawcookie() instead. The setrawcookie() function sends an HTTP cookie without URL encoding the cookie value. Arguments used in setrawcookie() are similar as for setcookie().


Deleting Cookies

If you want to remove a cookie from the user's browser, you must instruct the browser to delete it. To delete a cookie, call setcookie(), as before, using the same cookie name and any value (such as an empty string), and pass in an expires argument, i.e. a negative time value. This immediately expires the cookie on the browser, ensuring that it is deleted. You should also pass exactly the same path , domain , and other fields that you used when you first created the cookie to ensure that the correct cookie is deleted:

setcookie("pageviews", "", time() -3600, "/", "", false, true)

Sessions Explained

As mentioned above, cookies have some drawbacks in terms of security and data transfer. These issues can be overcome by using PHP sessions. Instead of storing data in the browser, a
PHP session stores data on the server, and associates a short session ID string (known as SID) with that data. The PHP engine sends a cookie containing the SID to the browser to store and sends the SID cookie back to the server when the URL is requested. In doing this the SID allows PHP to retrieve the session data and make it accessible to your script.
SIDs are unique, random, and almost impossible to guess, thus sessions are a lot more secure than cookies. Another advantage over cookies is that the information is already stored on the server and does not have to be transferred with every URL request, thus allowing for a great storage capacity. PHP stores session data in a temporary file on the server.

Creating Sessions

The session_start() function is used to start a PHP sessionin your script. If the session is new, a unique SID for the session is created and sent to the browser as a cookie called PHPSESSID (by default). If PHPSESSID already exists, the function uses this existing session. As with cookies, you must create the session before you output anything to the browser as session_start() needs to send the PHPSESSID cookie in an HTTP header when it creates a session. Session data is stored as keys and values in the $_SESSION superglobal array.

The following code shows a simple example of creating a user session. Note how the code begins with creation of the session, after which anything required for your user session must be decelared, such as conditions and functions. Important to note here is that this all takes place before any HTML data is output to the browser.

<?php session_start(); 
/* declare variables, constants, conditions and functions for your session here*/ 
<!DOCTYPE html>
<--enter your HTML markup code here-->

Destroying a Session

Sessions are automatically deleted when the user quits their browser as the PHPSESSID cookie's expires field is set to zero. However, sometimes you need to destroy a session immediately, e.g. emptying a shopping cart once a purchase has been completed. To do this use the session_destroy() function. This erases session data from the disk, however. data is still stored in the $_SESSION array until the current execution of the script ends. To ensure that all session data has been erased, you should also initialize the $_SESSION array.

$_SESSION = array(); session_destroy();

What about the PHPSESSID cookie stored in the user's browser? Upon the next visit, PHP will use this to recreate the emptied session. To really ensure that you have destroyed the session from both the server and the browser, you should also destroy the session cookie. The session_name() function returns the name of the session cookie (PHPSESSID by default).

if ( isset( $_COOKIE[session_name()] ) ) { 
    setcookie( session_name(), “”, time()-3600, “/” ); 
$_SESSION = array(); 

Cookies vs Sessions

Cookies can be created with a custom lifespan, from seconds to years and so can store data for a long time if needed. Sessions on the other hand are deleted once the browser is quite as the PHPSESSID cookie has its expires argument set to "0". As such cookies are best used if you need to store information over an extended period. Another advantage of cookies, having their data stored on the client, is that they work well when using multiple servers. As sessions store all information on the server side, only the server used for the initial URL request will store the information, thus sessions dont work as well when using multiple servers.

The advantage of sessions storing data on the server is that clients don't have access to the information you store about them, something which is very important if you store shopping baskets or other information you do not want your visitors to be able to edit by hand as they could do with cookie files. In addition. session data does not need to be transmitted with each url request. Another advantage of server side storage is there is greater storage capacity, whereas cookies are limited by the browser settings in this respect.

To summarise, if the information you're handling is not sensitive and it requires storage over an extended period then cookies are your best option. If you don't need semi-permanent data, then sessions are generally preferred, as they are easier to use, don't require data to be transferred with each url request, and they are destroyed as soon as your visitor closes the browser. If you have any particularly sensitive information, its recommended to store this in a database, then use the cookie to store an ID number to reference the data.

So Why Are They Called Cookies?

I did promise I'd tell this story at the beginning. There's no real answer unfortunately, however, there are a few cool theories jumping about. One theory suggests that cookies derive from an old Unix programme called Fortune Cookie which used a system not unlike the modern browser cookie to remember which fortunes you had already seen, enabling it to send you a new fortune each time it was used. A not so exciting thoery suggests they derive from Unix 'magic cookie' objects which are attached to a user or program and change depending on the areas entered by the user or program. My money is on the Cookie Monster theory. Apparently there was a guy who developed a large corporate mainframe accounting system who included a clever bit of code. Once he left the company, on ocassion the system would completely halt and display the message: "Gimme a cookie." The system would not return to normal until the operator entered "cookie". As his replacement couldn't figure out why this was happening they decided to document the cookie question and train operators to give the machine a cookie.