For security reasons, “standards” are set to 20 the maximum number of cookies sent to a domain.
We’ll be covering the following topics in this tutorial:
What about security?
There’s still a few years cookies frightened. Some laymen were convinced they were dangerous, they could execute malware on their computer or retrieve personal or confidential information. But this is not the case. A cookie is nothing more nor less than a text file very small. It can therefore not be executed or even launch programs alone. It is only used to store information for later use. However, nothing prevents a hacker program to be executed by the user (but without his knowledge) that will retrieve confidential or personal information, and then store them in a cookie and sends it creates the Web server. This latter will retrieve the information transmitted and used against the user.
Creating a cookie nevertheless calls for respect for some rules of safety and common sense. The cookie is stored on the hard disk of the client, its access there is not secure. A cookie can be read, modified or deleted without difficulty by a malicious user. It is therefore not advisable to store sensitive information such as:
• confidential information inside (password for example).
• easily identifiable connection identifiers as a login.
A cookie should generally be used only for statistical purposes of display or customization to the multi paging forms. And even in the latter case, the best solution would be to have recourse to the mechanism of the sessions.
Generating a cookie with setcookie ()
Creating a cookie based on the HTTP headers sent to the client browser by using the setcookie () function. This therefore implies that it will take the call before sending data to the browser (print (), echo (), html tag, white space …) under penalty of generating a type error “Warning: Can not send session cookie –headers already sent by … “.
Setcookie () may take up to 7 parameters. Only the first is mandatory as it sets the cookie name. It returns a boolean: true if successful and false if failure.
Signing of the setcookie () bool setcookie (string name [, string value [, int expire [, string path [, string domain [, bool secure [, bool httponly]]]]]])
The table below summarizes the values that can take each of these parameters.
|expire||Expiration date of the cookie in Unix timestamp format, ie the number of seconds since January 1, 1970|
|path||Path on the server in which the cookie is valid. If the value ‘/’ is specified then the cookie will be visible throughout the area. If ‘/ examples /’ is then clear the cookie will be visible in the / examples / and all its subfolders|
|domain||Domain on which the cookie is valid. If the value is ‘.domain.com’ then the cookie will be available on all domain (including sub-domains). If the value is ‘www.domain.com’ then cookie will be valid only in the subdomain ‘www’|
|secure||This parameter takes a boolean value for defining whether the cookie should be used in the context of HTTPS secure connection|
The following code illustrates how to create a cookie characterized by a name, a value and validity date of one month. It simulates the recording of the design of a site that the user prefers. With this cookie, the website will be displayed with the graphical theme automatically at the next visit of the user.
Creating a cookie <?php // Create the cookie setcookie ('designPrefer', 'meadow', time () + 3600 * 24 * 31); ?>
 When a cookie is created from a page, it is only available on the following page as it takes the browser sends the cookie to the server.
 A cookie whose expiration date is not specified is stored in the RAM of the computer and not on the hard drive. It will be deleted when closing the browser.
Playing a Cookie
When a user queries a site identified by a domain name, the browser sends to the server the list of cookies available for this area. PHP receives the then builds an associative array named $_COOKIE superglobal. The keys are the names of cookies and values to the values enshrined in them. It then becomes very easy to access the value of a cookie by calling the $_COOKIE array with the key that fits. The example below allows us to retrieve the cookie value that we created earlier.
Playing a cookie <! DOCTYPE html PUBLIC "- // W3C // DTD XHTML 1.1 // EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xml: lang = "en"> <html> <Head> <title> Reading a cookie! </title> </Head> <body> <p> Your favorite theme: <?php // Read the value of the cookie designPrefere echo $_COOKIE ['designPrefer']; // Display 'meadow' ?> </p> </body> </html>
 Add a key / value pair in $_COOKIE array does not create a new cookie.
 To change the value of a cookie, you must reuse the setcookie () function.
 For all the cookies used, you need to list the $_COOKIE array using a foreach () loop or a call to print_r ().
Deleting a cookie
To delete a cookie, you must again call setcookie (), passing as parameter the name of the cookie only. In our example we will use the following code to remove our designPrefer cookie.
Script to delete a cookie <?php // Delete the cookie designPrefer setcookie ('designPrefer'); ?>
The above code tells the browser to delete the cookie but does not remove the value in $_COOKIE array. We must therefore think of removing them. For this, we use the following script.
Script complete removal of a cookie <?php // Delete the cookie designPrefer setcookie ('designPrefer'); // Delete the value of the $_COOKIE unset ($_COOKIE ['designPrefer']); ?>
Storing complex types in a cookie
So far we have stored in our cookie value chain typeface. It is a primitive type. But it is also possible to store an entire table in a cookie. To achieve this, you must first convert it into character string and then rebuild it when received. This is what is called serialization (or folding, marshalling) and deserialization (or unfolding or unmarshalling). These two operations are performed using the serialize() and unserialize ().
Illustrate these principles from an example simulating the launch of a dice. Our cookie will be called “spears”. We also launched simulate the dice with the rand () function. All running will be stored in a vector (array to a numerically indexed dimension) that we serialization / deserialization for the purposes of the cookie.
Dice launched simulation and recording scores in a cookie <?php // Define data structures $NumberofDice = 0; // Number of dice spears $ListSerialized = ' '; // Serialized chain of cookie $ArrayofDice = array (); // Array of dice launched values
// Test the existence of the cookie
if (!empty ($_COOKIE [‘spears’]))
// Get the values in $ArrayofDice by deserialization
$ListSerialized = $_COOKIE [‘spears’];
$ArrayofDice = unserialize ($ListSerialized);
// We launch the dice again
$ArrayofDice  = rand (1,6);
// It serializes the table and creates the cookie
$ListSerialized = serialize ($ArrayofDice);
setcookie (‘spears’ , $ListSerialized, time()+ 3600 * 24);
// Calculate the number of dice thrown
$NumberofDice = count ($ArrayofDice);
<! DOCTYPE html PUBLIC “- // W3C // DTD XHTML 1.1 // EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns = “http://www.w3.org/1999/xhtml” xml: lang = “en”>
<title> launched simulation of a dice! </title>
You have launched <?php echo $NumberofDice; ?> Times the dice;
if ($NumberofDice > 0)
// It displays the contents of the table deserialized
foreach ($ArrayofDice as $Numberspears => $valuespears)
echo ‘<li> Launched n #’, ($Numberspears +1), ‘:’, $valuespears, ‘</ li> ‘;
Five times by calling the script, we simulate launched five dice. The result produced similarly there to.
Result of the script
You have launched 5 times the dice:
* Launched # 1: 4
* Launched # 2: 6
* Launched # 3: 3
* Launched # 4: 3
* Launched # 5: 3
* Launched # 6: 2
The main event of cookies use
Cookies thus are very useful in case of particular FIG. Among them, we can identify:
• safeguarding the preferred design of a site for an Internet user
• display the new messages since the last visit of the user
• display unread messages in the visitor forum
• fragmentation of a form across pages. The values sent on the first page are serialized and sent by the second cookie to which the deserialized visits counters
• the recognition of visitors having already voted in a poll.