A cookie is simply a
NAME = VALUE pair stored in the user’s browser.
- To set a cookie in PHP, use
- Then, we can use
$_COOKIE["NAME"]to get the cookie value.
- To remove a cookie –
setcookie("NAME", null, -1);
That covers the basic usage of cookies in PHP, but just what exactly are cookies and how do they work? Let us walk through more examples, read on!
ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
TABLE OF CONTENTS
|Download & Notes||Cookie Examples||Useful Bits & Links|
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTESIf you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.
EXAMPLE CODE DOWNLOAD
Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
1) SETTING COOKIES
1A) PHP SET COOKIES
<?php // ASK THE BROWSER TO SET A "COLOR" COOKIE WITH VALUE "RED" setcookie("Color", "Red");
As in the introduction above, all we need to set a cookie is
1B) PHP OUTPUTS “SET-COOKIE” HTTP HEADERS
To address a common confusion among beginners, cookies are not saved on the server side. What actually happens with
setcookie("Color", "Red") is that PHP will only output the HTTP response header
This is Chrome, but it is the same for all Chromium-based browsers – You can verify the HTTP headers by opening the developer’s console (F12 in most browsers), under Network > 1-set.php > Headers > (Server) Response Headers.
1C) BROWSER SAVES THE COOKIE
Yes, the browser is the one that actually saves the cookie. You can verify this by going under the Application > Cookies.
P.S. The browser will simply ignore the
Set-Cookie if cookies are disabled.
2) RETRIEVING COOKIE VALUES
2A) PHP SET COOKIES
<?php // (A) COOKIES ARE AUTOMATICALLY PARSED INTO $_COOKIE SUPERGLOBAL var_dump($_COOKIE); // (B) $_COOKIE IS AN ARRAY echo $_COOKIE["Color"];
As in the introduction above again, we use
$_COOKIE["NAME"] to retrieve a cookie value.
2B) BROWSER SENDS COOKIE TO SERVER
You should be able to guess this part – On subsequent visits, the browser sends the
Color=Red cookie back to the server. You can verify this under Network > 2-get.php > Headers > (Browser) Request Headers. PHP will automatically parse this into the
$_COOKIE superglobal, and we can use it just like a “regular array”.
3) UPDATING COOKIES
<?php // TO UPDATE A COOKIE, SIMPLY SET COOKIE AGAIN setcookie("Color", "Blue");
Captain Obvious to the rescue! To update a cookie, we use
setcookie() again to override the existing value.
4) ARRAYS IN COOKIES
<?php // (A) COOKIES CANNOT ACCEPT ARRAYS // (A1) SERIALIZE THE ARRAY setcookie("ARRAYA", serialize(["Foo", "Bar"])); // (A2) OR JSON ENCODE setcookie("ARRAYB", json_encode(["Hello", "World"]));
Take note that cookies can only store strings and numbers. For arrays, we have to use
json_encode() to turn the array into a string first.
<?php // (B) TO RETRIEVE THE ARRAY // (B1) UNSERIALIZE THE ARRAY $arra = unserialize($_COOKIE["ARRAYA"]); var_dump($arra); // (B2) JSON DECODE $arrb = json_decode($_COOKIE["ARRAYB"]); var_dump($arrb);
Then do the reverse of
json_decode() to get the array back.
5) DELETING COOKIES
<?php // SIMPLY SET A TIME IN THE PAST TO DELETE COOKIE setcookie("Color", null, -1);
Captain Obvious to the rescue again. To delete a cookie, set the expiry timestamp to
-1 or any date in the past.
EXTRA) MORE COOKIE SETTINGS
Some of you sharp code ninjas should have noticed there are a lot of “cookie setting columns” in the developer’s console. Yes, there are quite a lot of settings and restrictions we can set on cookies. This one is a little more on the intermediate-advanced side, but still, good to know:
expiresWhen the cookie expires. By default, this is
0– When the user closes the browser, the cookie disappears.
domainWhich domain the cookie is valid for. Quite an advanced topic that involves cross-origin requests (CORS). I will leave links below if you are interested.
pathUse this to restrict the path of where this cookie applies, defaults to
samesiteAnother CORS setting.
USEFUL BITS & LINKS
That’s all for the main tutorial, and here is a small section on some extras and links that may be useful to you.
Take extra note – Cookies are restricted to 4096 bytes. They are not meant to store crazy data like video files and such…
REFERENCES & LINKS
INFOGRAPHIC CHEAT SHEET
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!