THE ARRAY $_COOKIE

php logoThe preservation of the state as already mentioned can be done on the server with session files but also on the client, in this case we talk about cookies. If we want to delegate to the client the storage of data however not sensitive, the thing we need to do is send this information to the client, and we do that through the response headers. As we know when we make a request we make it through a browser within the address bar by specifying a URL.

THE SETCOOKIE() FUNCTION

Through this request other information travels between client and server thanks to the headers, server-side the request is parsed and a visible response is provided in the user’s browser. If we want to store information about the client send information through the response headers, we should not interact with the headers but use a setcookie() function;

set-Cookie

If we now go to the browser at http://localhost/corsi/php/ArraySuperglobali/setcookie.php open the Chrome browser tools with F12 -> Network tab -> refresh the page and click on setcookie.php we will see that in the Response Headers we have the following cookie.

set-Cookie

Now let’s create a new page pagina4.php and we make a var_dump of the array $_COOKIE. Let’s go to the browser again by typing the address of pagina4.php and we will have the following information. (Side figure).

S_COOKIE

Why do we have this information in the pagina4.php ? From the browser tools by clicking on pagina4.php in the response headers we have no cookie, however if we go inside the request headers we have a Cookie header with this information.

Cookie

In this case it is the client that sent this information to the server, only the first time we invoke setcookie() we send the information from the server to the client the client stores the information and in subsequent requests sends it to the server. We return to setcookie.php, comment out setcookie() and make a var_dump($_COOKIE). Also on this page we have the same information even though we have commented out the statement setcookie(). In this case it is the client that sends the information to the server, which reads it with the superglobal array $_COOKIE. If we close the Browser and reopen it the information is lost, the information was kept only for the previous session, if we want to keep the information even when the user closes the Browser we have to specify an expiration in setcookie().

Expire Cookie

ROLE OF COOKIES IN SESSIONS

As for the sessions, we are missing a step in understanding the mechanism. We start a session and display its session_id(). We simultaneously open two browsers to simulate two different requests made by two different clients.

open two browser

We go into visual studio code and open the built-in terminal, going to the folder where the sessions we now know well are stored.

sessions

We next store a value in the array $_SESSION by setting the color to green.

vs. tails

We make the request in the Chrome browser correctly displaying the color green. Now let’s change the color, say Blue. We go to Firefox and read Blue correctly. Let’s go and read the session files and we will see that the session associated with Chrome has the value Green, while the session associated with Firefox has the color Blue. The point is: How does the server associate a session with Chrome and a session with Firefox?

THE ROLE OF COOKIES

Suppose we are two different clients, so requests made from completely different devices, since the HTTP protocol is stateless whenever we make a request with a device for the server we are complete strangers; therefore, there must be a mechanism such that when a request is made with Chrome the server goes to read the right session, item for Firefox. Let’s delete the two session files and clear Firefox’s cache CTRL-SHIFT-CANC. We check The Session ID again, go back into Firefox but before making the request open the developer tools with F12.

Session_ID

We make the request again and in the response header we have a Set-Cookie with value The generated session ID.

Firefox

This means that the server sends the session identifier to the client. If we now make a new request we will see that in the response header there are no Cookies (only the first time the server sets Set-Cookie) on subsequent requests it will be the client that returns the information in the Request Header to the server, which is why we are able to associate any client with its sessions.

DEEPENING

In PHP, the $COOKIE superglobal is an associative array that is used to access data stored in cookies sent from the client’s browser to the server. Cookies are small text files that can be used to store data on the user’s computer, such as preferences or session information, and are often used to maintain state between different pages of a Web site.

Use of $COOKIE:

-Access to Cookies: You can access the value of a specific cookie by using the cookie name as a key in the $COOKIE array.

// Supponiamo che esista un cookie chiamato “utente”
if(isset($_COOKIE[‘utente‘])) {
        echoIl valore del cookie ‘utente’ è: “ . $_COOKIE[‘utente‘];
} else {
        echoIl cookie ‘utente’ non è stato impostato.“;
}

– Setting Cookies: To set a cookie, you use PHP’s setcookie() function. Here is an example of how to set a cookie:

// Imposta un cookie chiamato “utente” con il valore “Mario” che scade in 30 giorni
setcookie(“utente“, “Mario“, time() + (86400 * 30), “/”); // 86400 = 1 giorno

-Deleting a Cookie: To delete a cookie, you must set it with an expiration date in the past:

// Cancella il cookie chiamato “utente”
setcookie(“utente“, “”, time() – 3600, “/“);

Important notes:

1. Timing: Cookies are sent by the browser only during the next request, so if you set a cookie and then immediately try to read it with $COOKIE, you will still not see the updated value.

2. Security: Cookies can contain sensitive data, so it is important to use them carefully. It is recommended that you use the HttpOnly option when you set a cookie, so that the cookie cannot be accessed through JavaScript.

setcookie(“utente“, “Mario“, time() + (86400 * 30), “/“, “”, false, true); // HttpOnly è il settimo parametro

3. Properties: Cookies are domain and path specific, meaning that a cookie set for one domain will not be available for another domain.

This superglobal is particularly useful for user session management, preference tracking, and other features that require maintaining state between HTTP requests.

LINKS TO PREVIOUS POSTS

THE PHP LANGUAGE

LINK TO THE CODE ON GITHUB

GITHUB