Cookies are small pieces of data that can be stored on the client/browser. Once stored, they are automatically sent from the browser to the server with every request, allowing us to manipulate them using PHP.
Cookies are stored in a key-value pair and are used very commonly on the web, especially for things like user settings and preferences.
A look at delicious cookies in real life.
Setting a Cookie in PHP
Set a cookie using PHP's built-in setcookie() function. Here's the syntax for the function:
This creates a cookie set to expire in 30 days with the name city and value Miami.
You can validate that the cookie has been set by right-clicking anywhere on the page and hitting Inspect Element (or just opening your Developer Tools). Then head on over to the Application tap at the top, then checking under the Cookies section under Storage on the left. This window displays all of our cookies and you should see the one you created here.
A look at cookies set in PHP.
Accessing Cookie Values in PHP
Now that the cookie is set, the browser will now automatically send the entire cookie with every request for as long as the cookie isn't expired. This means we can now access the cookie on the server since it has been sent to us with the request.
PHP automatically creates an associative array with all the cookies sent in the request in the superglobal variable named $_COOKIE. This means that you can access the value of any cookie by passing in the key/name, just like you would access any associative array in PHP.
Accessing the cookie we set earlier is as easy as this:
PHP
<?phpecho($_COOKIE['city']);
?>
HTML
Miami
Keep in mind that cookies can be manipulated by the user. This means that while they're useful, they cannot be trusted to hold sensitive information. This also means that you cannot expect any cookie to come from the client with a 100% certainty. Because of this, it is recommended that you first check if the cookie exists before trying to access it.
Since cookies are provided to us in an associative array, you can also display every single one like could with any associative array. This can be useful for debugging any code that uses cookies.
Print all your cookies out like so:
PHP
<?phpprint_r($_COOKIE);
?>
Deleting Cookies in PHP
You can delete a cookie by using the same function used to set them in the first place, the setcookie() function. Remember that browsers will automatically remove expired cookies. That means all you need to do is set the expiration date to any time in the past, and the browser will take care of the rest.
All you need is the name of the cookie and exactly where the cookie was set to be active, along with any time in the past:
This takes our city cookie and sets its time to 60 seconds in the past. Once that happens, the browser will recognize that this cookie has expired and remove it for us.