Cookies In PHP (Very Simple Guide & Examples)

Welcome to a quick tutorial and examples of how to use cookies in PHP. So you have heard of this “cookie thing” and wonder how to use it in PHP?

A cookie is simply a NAME = VALUE pair stored in the user’s browser.

  • To set a cookie in PHP, use setcookie("NAME", "VALUE");
  • 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.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Cookie Examples Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If 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.

 

 

PHP COOKIE EXAMPLES

All right, let us now get into the examples of working with cookies in PHP.

 

1) SETTING COOKIES

1A) PHP SET COOKIES

1-set.php
<?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 setcookie("NAME", "VALUE").

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 Set-Cookie: Color=Red.

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

2-get.php
<?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

3-update.php
<?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

4a-set-array.php
<?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.

4b-get-array.php
<?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 unserialize() or json_decode() to get the array back.

 

 

5) DELETING COOKIES

5-delete.php
<?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

6-more.php
<?php
set_cookie("FOO", "BAR", [
  "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
]);

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:

  • expires When the cookie expires. By default, this is 0 – When the user closes the browser, the cookie disappears.
  • domain Which 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.
  • 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 with document.cookie.
  • samesite Another 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.

 

COOKIE RESTRICTION

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

Cookies In PHP (Click to Enlarge)

 

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!

1 thought on “Cookies In PHP (Very Simple Guide & Examples)”

Leave a Comment

Your email address will not be published. Required fields are marked *