Use of PHP Cookies

This new tutorial introduces the Cookie mechanism in PHP.

Together we will define what a cookie is and what it is used for. We will then discuss the security principles related to cookies. Later we will learn how to generate and read the content of a cookie. We will finish this tutorial on clearing the cookie, storing complex type values ​​by serialization/deserialization before concluding on the most frequent use cases.


  • What is a web cookie?
  • What about security?
  • Cookie generation with setcookie()
    • Setcookie function definition
  • Reading a cookie
  • How to Clear Cookies in PHP
  • Storing complex values ​​in a Cookie
  • The main use cases of cookies

The Cookies mechanism was invented by the Netscape company in order to overcome certain weaknesses of the HTTP protocol, but also to broaden the possibilities of the relationship between the client and the website. Its function is the storage, for a certain period of time, of information about the user (his nickname, date of last connection, age, preferences…).

In practice, cookies are simple text files that cannot exceed 4KB. They are stored on the user’s hard drive and are managed by browsers (Firefox, Internet Explorer, Safari, Opera, AvantBrowser…). Its acceptance is subject to browser filters. In fact, the latter are capable of rejecting cookies. Therefore, its use must be scrupulously considered.

For security reasons, the “standards” have set in 20 the maximum number of cookies sent to the same domain.

What about security?

Until a few years ago cookies were scary. Some users were convinced that they were dangerous, that they could run malicious programs on their computers or recover personal or confidential information. It is not like this. A Cookie is nothing more and nothing less than a very small text file.

It cannot be run or even run programs by itself. It is only used to store information for later reuse.

On the other hand, nothing prevents a pirate program from being executed by the user (but without their knowledge) that will retrieve confidential or personal information, and then store it in a cookie that it creates and sends to the web server. The latter will then retrieve the transmitted information and use it against the user.

The creation of a Cookie requires, however, the respect of some security rules and common sense. As the cookie is stored on the client’s hard drive, access to it is not secure. A cookie can easily be read, modified or deleted by a malicious user. Therefore, it is strongly advised not to store sensitive information such as:

  • Confidential information inside it (for example, the password).
  • Login identifiers easily identifiable as a login.

In general, a cookie should only be used for statistical purposes, to personalize the screen or for the multipage of the forms. And even in the latter case, the best solution would be to use the session mechanism.

Cookie generation with setcookie()

The creation of a cookie is based on sending HTTP headers to the client’s browser using the setcookie() function. This implies that it must be called before any data is sent to the browser (print(), echo(), html tag, white space…) otherwise it will generate a “Warning: Cannot send” error. the session cookie – the headers have already been sent…”. ».

The setcookie() function can receive up to 7 parameters. Only the first one is required because it defines the name of the cookie.

Returns a boolean: true on success, false on failure.

Setcookie function definition

setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] ) : bool

The following flag illustrates the creation of a cookie with a name, a value, and a validity date of one month. Simulates the registration of a site design that the user prefers. Thanks to this cookie, the site will be displayed with this graphic theme automatically the next time the user visits the site.

Basic usage example:

  // Creación de una cookie
  setcookie('cookie_prueba','valor de la cookie',time()+3600*24*31);

1] When a one page cookie is created, it is only available on the next page (at the next visit) because the browser must send the cookie to the server.2]A cookie with an unspecified expiration date is stored in the computer’s RAM and not on the hard drive. It will be deleted when the browser is closed.

When an Internet user consults a website identified by a domain name, their browser sends the server a list of cookies available for that domain. PHP receives them and then builds a superglobal associative array called $_COOKIE.

The keys correspond to the names of the cookies and the values ​​to the values ​​written to them. So it becomes very simple to access the value of a cookie by calling the $_COOKIE array with the appropriate key. The following example allows us to retrieve the value of the cookie we created earlier.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "">
<html xmlns="" xml:lang="es">
    <title>Lectura de una cookie !</title>
      El valor de tu cookie es: 
        // Lecture de la valeur du cookie designPrefere
        echo $_COOKIE['cookie_prueba'];    // Muestra el valor "valor de cookie"

Observations :

1]Adding a key/value pair to the $_COOKIE array does not create a new cookie. 2]To change the value of a cookie, you have to reuse the setcookie() function.[3] To find out all the cookies used, you have to list the $_COOKIE array using a foreach() loop or a print_r() call.

How to Clear Cookies in PHP

To delete a cookie, you have to call the setcookie() function again, passing the cookie name only as a parameter. In our example, we will use the following code to clear our DesignPrefere cookie.

  // Borrado de la cookie

The above code tells the browser to clear the cookie but does not clear the $_COOKIE table value. So you have to remember to delete both. To do this, we use the following example.

  // Borrado de la cookie creada
  // Borrado de la clave de la variable COOKIE

So far we have stored a simple string value in our cookie. So it’s a primitive type. But it is also possible to store a complex array in a cookie.

To perform this operation, it is necessary to transform the cookie into a character string and then rebuild it when received.. This is called serialization (or folding, sorting) and deserialization (or unfolding or unsorting). Both operations are performed using the functions serialize() and unserialize().

Let’s illustrate these principles with an example that simulates the throw of a dice. Our cookie will be called “rollFrom”. We will also simulate the roll of the dice with the rand() function. All releases will be stored in a vector (numerically indexed one-dimensional array) that we will serialize/deserialize into the cookie.

Simulation of dice rolls and recording of scores in a cookie:

  // Definición de las estructuras
  $nombreLancesDe = 0;      // Número de lanzamientos
  $listeSerialisee = '';      // Cadena de serialización de la cookie
  $listeLancesDe = array();    // Tabla de valores de los lanzamientos
  // Comprobación de la existencia de la variable
    // Recuperar el valor de la cookie en la variable $listeLancesDe para la desealización
    $listaSerializada= $_COOKIE['lanzamientos'];
    $listaDeLanzamientos= unserialize($listaSerializada);
  // Almacenamos cada lanzamiento
  $listaDeLanzamientos[] = rand(1,6);
  // Serializar de nuevo el array
  $listaSerializada= serialize($listaDeLanzamientos);
  setcookie('lanzamientos', $listaSerializada, time()+3600*24);
  // Calcular el número de lanzamientos
  $numeroDeLanzamientos= count($listaDeLanzamientos);
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "">
<html xmlns="" xml:lang="fr">
   <title>Simulación de lanzamientos de un dado!</title>
     Has lanzado el dado <?php echo $nombreLancesDe; ?>  veces con los siguientes resultados :
      if($numeroDeLanzamientos> 0)
        echo '<ul>';
        // Recoerremos el array de lanzamientos
        foreach($listaDeLanzamientos as $numeroDeLanzamientos => $valor)
          echo '<li>Lanzamiento n#', ($numeroDeLanzamientos+1) ,' : ', $valor,'</li>';
        echo '</ul>';

By calling the script five times, we simulate five rolls of the dice. The result is similar to this:

You have rolled the die 6 times with the following results:
* Release #1 : 4
* Release#2 : 6
* Release #3 : 3
* Release #4 : 3
* Release #5 : 3
* Release#6 : 2

The main use cases of cookies

Therefore, cookies are very useful in special cases. Among them, we can list:

  1. Saving the preferred layout of a website for a user to use. the display of new messages since the Internet user’s last visit
  2. The display of unread messages by the visitor in a forum.
  3. The fragmentation of a form in several pages. The values ​​sent on the first page are serialized and sent by cookie to the second page which will deserialize them.
  4. Visit counters.
  5. Recognition of visitors who have already voted in a poll

We will remember that cookies are an effective way to retain small amounts of information about a user. However, for security reasons, their size is limited to 4KB and their number to 20 for the same domain.

Therefore, they should not be used to transfer large amounts of data, but only to store information for statistical purposes or to display customizations.

Leave a Reply