Categories
PHP

Understanding HTTP Cookies

How to send and retrieve data as part of the HTTP header in the form of a cookie.

  1. Creating Cookies
  2. Changing Cookies
  3. Reading Cookies
  4. Deleting Cookies

Hypertext Transfer Protocol (HTTP) is a stateless protocol. Each HTTP request a browser sends to a web server is independent of any other request. The stateless nature of HTTP allows users to browse the Web by following hypertext links and visiting pages in any order.

However, applications that require user interaction can’t be implemented as a series of unrelated, stateless web pages. An often-cited example is a shopping cart in which items are added to the cart while searching or browsing a catalog. The state of the shopping cart (the selected items) needs to be stored somewhere. When the user requests the order page, the items for that user need to be displayed.

You can overcome this limitation in several ways. The basic idea is to send some information with the HTTP response; to try to achieve that, this information is sent back with all subsequent requests to that server. The following possibilities exist:

  • Sending the data via POST (that is, a form is required each time)
  • Sending the data via GET (that is, by appending this information to the request’s URL), for example:
    http://brainbell.com/cart.php?itemId=40
  • Sending the data as part of the HTTP header (in the form of a cookie)

HTTP Cookies

A cookie is a named piece of information that is stored in a web browser. Cookies are used to store an application state in the web browser. As with data sent with the GET or POST methods, cookies are sent with HTTP requests made by a browser.

A cookie is usually sent from the web server to the client (web browser) in the Set-Cookie header field as part of an HTTP response. See an example HTTP response:

Cookies are set as part of the HTTP header.

The web browser that receives this response remembers the cookie and includes it as the header field Cookie in subsequent HTTP requests to the same web server. For example, if a browser receives the response just shown, a subsequent request has the following format:

Cookies are set as part of the HTTP header.

Cookies can be included in an HTTP response using the header( ) function; however, the developer needs to know how to encode the cookie name, value, and other parameters.

Creating a Cookie

<?php
 setcookie('key','value');
 echo 'Cookie set';

To simplify cookie creation, PHP provides the setcookie( ) function that generates a correct header field. The setcookie( ) function is called with seven parameters, although only the first $name is required:

<?php
//Syntax
setcookie(
   string $name,
   string $value = "",
   int $expires_or_options = 0,
   string $path = "",
   string $domain = "",
   bool $secure = false,
   bool $httponly = false 
): bool
  1. $name The name of the cookie.
  2. $value (optional) The value of the cookie.
  3. $expires_or_options The expiry date (in UNIX epoche format). For example, time()+60*60*24*7 will set the cookie to expire in 7 days. If the value is set to 0 or not provided, the cookie will expire at the end of the session (when the browser closes).
  4. $path The path on the web server from which the cookie may be accessed:
    • / means the cookie will be available within the entire domain
    • /tutorials/ means the cookie will only be available within the brainbell.com/tutorials/ directory and all sub-directories such as brainbell.com/tutorials/php/.
  5. $domain The domain from which the cookie may be accessed.
    To make the cookie available to the whole domain (including all subdomains of it), simply set the value to the domain name i.e. brainbell.com.
  6. $secure When true the cookie only be sent on secure connections (HTTPS/SSL).
  7. $httponly When true the cookie won’t be accessible by JavaScript.

Note: Cookies are sent as part of the HTTP header, they have to be created before any output is sent out (unless you are using output buffering). Otherwise, you receive an error message Cannot modify header information....

Example: Sending Multiple Cookies

<?php
 $expireOneDay = time()+86400; // one day
 $expire30Days = $expireOneDay * 30;

 /* Following cookie is accessible by www.brainbell.com/php/
    and sub-directories i.e. www.brainbell.com/php/images/
 */ 
 setcookie(
    'oneDay',
    'Single day life',
     $expireOneDay,
     '/php/',
     'www.brainbell.com'
   );
  
 /* Following cookie is accessible by brainbell.com 
    and all sub-domains i.e. www.brainbell.com
 */ 
 setcookie(
    'ThirtyDays',
    'Thirty days life',
     $expire30Days,
     '/',
     'brainbell.com'
   );

Modifying a Cookie

To modify a cookie, just re-send it after modifying its values (value, expiry date, etc.):

<?php

 $expire = time() + 86400; //one day
 
 //Modify cookie if already set
 if ( isset($_COOKIE['key']) ) {
  setcookie('key',1, $expire, '/');
 }
 else {
  setcookie('key',100, $expire, '/');
 }

Reading Out Cookies

When an HTTP request that contains cookies is processed, PHP makes the values of the cookies available to the script in the global associative array $_COOKIE.

The following example tests to see if the $count has been set from a cookie, and either sets the value to 1 or increments $count accordingly. The script also creates a cookie named visits, with the value set to the $count.

Example: Count your visits on a web page with cookies

<?php
 $visits = 1;
 if ( isset($_COOKIE['key']) )
  $visits += (int) $_COOKIE['key'];

 $expire = time()+86400; // one day
 setcookie('key',$visits, $expire, '/', 'brainbell.com');
  
 echo "You've opened this page $visits times";
 
 /* Prints 1 on first visit 2 on second visit and so on
 You've opened this page 1 time
 You've opened this page 19 time*/

Cookies can be used for simple applications that don’t require complex data to be kept between requests. However, there is a limit on the number and size of cookies that can be set: a browser can keep only the last 20 cookies sent from a particular domain, and the values that a cookie can hold are limited to 4 KB in size.

Example: Reading Multiple Cookies

<?php
 foreach ($_COOKIE as $name => $value) {
  echo "$name: $value<br>";
 }

Deleting a Cookie

To delete a cookie set its value to an empty string, set an expiry date that is in the past and send the cookie with the same name again. The following code implements this and deletes the cookie that has been sent by the previous code. Here, both methods are combined: The cookie value is set to an empty string, and the expiry date is in the past:

<?php
 setcookie('key','', 1, '/');

If you try to set the expiration date to 0, PHP just skips this parameter, so this does not work. You do have to provide a positive parameter, even if it’s 1 (which means Thursday, 1 January 1970, 00:01:00 UTC).


Cookies and Sessions: