what is a cookie in php

In this article we will see, in detail, what cookies are and how to make the most of them, using one of the most popular languages: PHP.

What is a cookie

A cookie is nothing more than a small text file that allows you to store a small amount of data (approximately 4 KB) on the user’s computer. They are typically used to keep track of information such as the username that the site can retrieve to personalize the page when the user visits the site for the next time.

Therefore, every time the browser makes a new request to the server, all cookie data is automatically sent to the server within the request itself.

How to set a cookie in PHP

The setcookie () function is used to set and create a cookie in PHP. Make sure you call this function before generating or outputting your script otherwise the cookie will not be set. The basic syntax of this function is:

setcookie ( name , value , expires , path , domain , secure );

The setcookie () parameters can be summarized as follows:

nameThe name of the cookie.
ValueThe value of the cookie. Do not store sensitive information as this value is stored in the computer of the user, and consequently this data could be read by malicious people.
expiresThe expiration date in UNIX timestamp format. After this time the cookies will become inaccessible, i.e. the value of a cookie will no longer be readable. Therefore its default value will be 0.
PathSpecify the path on the server for which the cookie will be available. If set to /, the cookie will be available within the entire domain. Therefore, each script, present within the domain, will be able to retrieve and exploit the value of the cookie.
DomainSpecify the domain for which the cookie is available, for example www.example.com.
SecureThis field, if present, indicates that the cookie should only be sent if a connection exists Secure HTTPS.
Parameters function setcookie

Please note that if the cookie expiration date is omitted or set to 0, the cookie will expire at the end of the session, i.e. when the browser is closed.

Here is an example that uses the setcookie () function to create a cookie named username and assign it the value John Carter. It is also specified that the cookie will expire in 30 days (30 days * 24 hours * 60 min * 60 sec).


   // ----------------
   // Setting a cookie
   // ----------------
   setcookie("username", "John Carter", time()+30*24*60*60);

It is important to point out that all the parameters of the setcookie function are optional except the name. In the event that an argument is omitted, it is advisable to replace it with double quotes (“”). To omit the expiration of the cookie, set the relative parameter to 0.

A web developer never stores sensitive data within a cookie, such as the password for access to a portal or other … so if it is necessary to save sensitive data securely, it is advisable to use sessions.

Access to cookie value

PHP offers a whole series of global variables that the developer can exploit to better manage the functionality that a web app in production requires. One of these variables is the $ _COOKIE global variable in PHP, it is used to retrieve the value of a cookie. It is usually an associative array that contains a list of all cookie values sent by the browser in the current request, encoded by the name of the cookie itself.

You can access the value of a single cookie using standard array notation, for example, to view the username cookie set in the previous example, you can use the following code.


   // ------------------------------------
   // Accessing an individual cookie value
   // ------------------------------------
   echo $_COOKIE["username"];

The PHP code from the previous example produces the following output:

John Carter

It is a good idea to always check if a cookie is set or not before accessing its value. To do this you can use PHP’s isset () function:


   // ----------------------------------------
   // Verifying whether a cookie is set or not
   // ----------------------------------------
      echo "Hi" . $_COOKIE["username"];
   } else{
      echo "Welcome…!";

You can also use PHP’s print_r () function like this: print_r ($ _ COOKIE); to see the $_COOKIE associative array structure, just like you do with other types of arrays.

Removal of cookie

You can delete a cookie by always invoking the setcookie () function with the cookie name and any value (such as an empty string, for example), however this time you need to set the expiration date to the past, as shown in the following example:


   // -----------------
   // deleting a cookie
   // -----------------
   setcookie("username", "", time()-3600);

To make sure that the cookie is deleted correctly, you should go to the setcookie function, exactly the same parameters that you used when you created the cookie.

Fonte: https://www.tutorialrepublic.com/php-tutorial/php-cookies.php

Seguimi su
Latest posts by Antonio Lamorgese (see all)

Antonio Lamorgese

Network administrator, web developer and expert in SEO practices. After years of industry experience, I have created a PHP code generator. Find out more at https://www.phpcodewizard.it.