Cookies In PHP

Posted by in Articles, PHP, Programming

In this post I’ll write about cookies in php that are very useful for retaining information through repeated visits by a browser.. Here , I’ll cover PHP’s session-tracking system in details.


A cookie is basically a string that contains several fields. A server can send one or more cookies to a browser in the headers of a response. Some of the cookie’s fields indicate the pages for which the browser should send the cookie as part of the request. The value field of the cookie is the payloadservers can store any data they like there (within limits), such as a unique code identifying the user, preferences, etc.

setcookie( ) function


setcookie(name [, value [, expire [, path [, domain [, secure ]]]]]);

This function creates the cookie string from the given arguments and creates a Cookie header with that string as its value. Because cookies are sent as headers in the response, setcookie( ) must be called before any of the body of the document is sent. The parameters of setcookie( ) are:


A unique name for a particular cookie. You can have multiple cookies with different names and attributes. The name must not contain whitespace or semicolons.


The arbitrary string value attached to this cookie. The original Netscape specification limited the total size of a cookie (including name, expiration date, and other information) to 4 KB, so while there’s no specific limit on the size of a cookie value, it probably can’t be much larger than 3.5 KB.


The expiration date for this cookie. If no expiration date is specified, the browser saves the cookie in memory and not on disk. When the browser exits, the cookie disappears. The expiration date is specified as the number of seconds since midnight, January 1, 1970, GMT. For example, pass time( )+60*60*2 to expire the cookie in two hours’ time.


The browser will return the cookie only for URLs below this path. The default is the directory in which the current page resides. For example, if /store/front/cart.php sets a cookie and doesn’t specify a path, the cookie will be sent back to the server for all pages whose URL path starts with /store/front/.


The browser will return the cookie only for URLs within this domain. The default is the server hostname.


The browser will transmit the cookie only over https connections. The default is false, meaning that it’s okay to send the cookie over insecure connections.

How To Access To Cookie

you can access that cookie through the $_COOKIE array. The key is the cookie name, and the value is the cookie’s value field. For instance, the following code at the top of a page keeps track of the number of times the page has been accessed by this client:

$page_accesses = $_COOKIE['accesses'];
setcookie('accesses', ++$page_accesses);

Example 1 – How To Use Cookies

HTML page that gives a range of options for background and foreground colors:

Example 1-1

<head><title>Set Your Preferences</title></head>
<form action="prefs.php" method="post">

<select name="background">
<option value="black">Black</option>
<option value="white">White</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select><br />

<select name="foreground">
<option value="black">Black</option>
<option value="white">White</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select><p />

<input type="submit" value="Change Preferences">

The form in Example 1-1 submits to the PHP script prefs.php, which is shown in Example 1-2. This script sets cookies for the color preferences specified in the form. Note that the calls to setcookie( ) are made before the HTML page is started.

Example 1-2

 $colors = array('black' => '#000000',
                 'white' => '#ffffff',
                 'red'   => '#ff0000',
                 'blue'  => '#0000ff');

 $bg_name = $_POST['background'];
 $fg_name = $_POST['foreground'];

 setcookie('bg', $colors[$bg_name]);
 setcookie('fg', $colors[$fg_name]);
<head><title>Preferences Set</title></head>

Thank you. Your preferences have been changed to:<br />
Background: <?= $bg_name ?><br />
Foreground: <?= $fg_name ?><br />

Click <a href="prefs-demo.php">here</a> to see the preferences
in action.


The page created by Example 1-2 contains a link to another page, shown in Example 1-3, that uses the color preferences by accessing the $_COOKIE array.

Example 1-3

<head><title>Front Door</title></head>
$bg = $_COOKIE['bg'];
$fg = $_COOKIE['fg'];
<body bgcolor="<?= $bg ?>" text="<?= $fg ?>">
<h1>Welcome to the Store</h1>

We have many fine products for you to view.  Please feel free to browse
the aisles and stop an assistant at any time.  But remember, you break it
you bought it!<p>

Would you like to <a href="prefs.html">change your preferences?</a>


There are plenty of caveats about the use of cookies. Not all clients support or accept cookies, and even if the client does support cookies, the user may have turned them off. Furthermore, the cookie specification says that no cookie can exceed 4 KB in size, only 20 cookies are allowed per domain, and a total of 300 cookies can be stored on the client side. Some browsers may have higher limits, but you can’t rely on that. Finally, you have no control over when browsers actually expire cookiesif they are at capacity and need to add a new cookie, they may discard a cookie that has not yet expired. You should also be careful of setting cookies to expire quickly. Expiration times rely on the client’s clock being as accurate as yours. Many people do not have their system clocks set accurately, so you can’t rely on rapid expirations.