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.



Cookies

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

Syntax

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:

name

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.

value

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.

expire

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.

path

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/.

domain

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

secure

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:

<?php
$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

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

Background:
<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 />

Foreground:
<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">
</form>
</body>
</html>

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

<?php
 $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]);
?>
<html>
<head><title>Preferences Set</title></head>
<body>

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.

</body>
</html>

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


<html>
<head><title>Front Door</title></head>
<?php
$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>

</body>
</html>

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.