Welcome to a beginner’s tutorial on how to use cookies in PHP. So you have heard of this “cookie thing” and wonder how to use it in PHP? Let us walk through some super simple examples in this guide, read on!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
WHAT ARE COOKIES?
Once upon a time in the Stone Age of the Internet, it is a paradise for “privacy lovers”.
- HTTP is a “stateless protocol” – The user requests a web page, and HTTP returns the web page. The end. There is no such thing as “tracking” and “identifiable data”.
- “Absolute privacy” may sound good, but if we cannot track which user is which – There is no way to implement “shopping carts”, and cannot process transactions securely.
- So cookies were introduced, it is nothing but a small piece of data saved in the browser – Mostly used to track users, save some preferences, and store temporary data.
PART 1) PHP COOKIE BASICS
1A) SET COOKIE
<?php
// (A) SET A "COLOR" COOKIE WITH VALUE "RED"
setcookie("Color", "Red");
To set a cookie, all we need is setcookie("NAME", "VALUE")
.
1B) GET COOKIE
<?php
// (A) COOKIES ARE AUTOMATICALLY PARSED INTO $_COOKIE SUPERGLOBAL
print_r($_COOKIE);
// (B) $_COOKIE IS AN ARRAY
echo $_COOKIE["Color"];
PHP will automatically parse cookies into $_COOKIE
, and we can pretty much access it like a “normal array”.
1C) UPDATE & APPEND COOKIES
<?php
// (A) TO UPDATE A COOKIE, SIMPLY SET COOKIE AGAIN
setcookie("Color", "Blue");
// (B) OR CREATE MORE COOKIES
setcookie("Hello", "World");
To change the value of a cookie, we simply call setcookie()
again. We can also create more cookies as required.
PART 2) ARRAYS IN COOKIES
2A) SET ARRAY IN COOKIE
<?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 serialize()
or json_encode()
to turn the array into a string first.
2B) GET ARRAY IN COOKIE
<?php
// (B) TO RETRIEVE THE ARRAY
// (B1) UNSERIALIZE THE ARRAY
$arrA = unserialize($_COOKIE["ARRAYA"]);
print_r($arrA);
// (B2) JSON DECODE
$arrB = json_decode($_COOKIE["ARRAYB"]);
print_r($arrB);
Then do the reverse of unserialize()
or json_decode()
to get the array back.
PART 3) DELETING COOKIES
<?php
// (A) SIMPLY SET A PAST TIME TO DELETE COOKIE
setcookie("Color", null, -1);
// (B) $_COOKIE WILL NOT REFLECT THE CHANGE IMMEDIATELY!
print_r($_COOKIE); // $_cookie["color"] still exists
// (C) MANUALLY UNSET TO REMOVE IMMEDIATELY
unset($_COOKIE["Color"]);
print_r($_COOKIE); // $_cookie["color"] gone
- (A) To delete a cookie, we have to do a roundabout way to set the expiry timestamp to
-1
(or any date in the past). - (B & C) Take note though,
$_COOKIE
will not reflect the changes immediately. You will have to manuallyunset($_COOKIE["NAME"])
to remove the key/value for the current session.
PART 4) ADVANCED COOKIE SETTINGS
<?php
set_cookie("KEY", "VALUE", [
"expires" => time() + 3600, // EXPIRES 1 HOUR (3600 SECS) FROM NOW
"domain" => ".site.com", // THIS COOKIE IS FOR *.SITE.COM
"path" => "/", // APPLICABLE TO ALL PATHS
// "path" => "/products", // APPLICABLE TO SITE.COM/PRODUCTS ONLY
"secure" => true, // APPLICABLE ON HTTPS ONLY
"httponly" => true, // JAVASCRIPT CANNOT ACCESS THIS COOKIE
"samesite" => "None" // FOR CORS - NONE, LAX, OR STRICT
]);
Over the years, cookies have become more than “a small piece of data”. It is used to track users and for secure operations. Yes, there are quite a lot of settings and restrictions we can set on cookies. This is on the intermediate-advanced side, but still, good to know:
expires
When the cookie expires. By default, this is set to0
– The cookie disappears when the user closes the browser.domain
The domain where the cookie is valid. By default,site-a.com
can only set cookies that belong tosite-a.com
. Whilesite-a.com
can set cookies forsite-b.com
, this is called “cross origins” (CORS) and an advanced topic. Will leave links below if you are interested.path
Use this to restrict the path of where this cookie applies, defaults to/
(entire site).secure
HTTPS only.httponly
Can only be used in HTTP calls, cannot be accessed with Javascript. Yes – Javascript can also access cookies withdocument.cookie
.samesite
Another CORS setting.
EXTRAS
That’s all for the main tutorial, and here is a small section on some extras and links that may be useful to you.
COOKIE RESTRICTIONS
- Cookies are restricted to 4096 bytes, they are not meant to store entire files.
- By default,
site-a.com
can only set cookies that belong tosite-a.com
. - By default,
site-a.com
will only accept cookies that are marked “this cookie belongs tosite-a.com
“. - It is possible to share cookies between multiple sites, but that is an advanced topic. Follow the “PHP CORS Cookie” link below if you want to learn more.
HOW COOKIES ACTUALLY WORK
PHP OUTPUT “SET-COOKIE” HTTP HEADERS
To address the common confusion once again, cookies are not saved on the server. What actually happens with setcookie("Color", "Red")
is that PHP will only output the HTTP header Set-Cookie: Color=Red
.
THE BROWSER SAVES THE COOKIE
When the browser receives Set-Cookie: Color=Red
, it will create and save the cookie.
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; PHP parses this into $_COOKIE
.
LINKS & REFERENCES
- Set Cookie – PHP
- Cookie Superglobal – PHP
- Cookie – MDN
- Set CORS Cookie In PHP – Code Boxx
THE END
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!
Thank you for your kindness in sharing your knowledge. Much appreciated.