How to Create and Remove Cookies in PHP Web Applications and How Do They Work

First I explain basic idea of cookies in web applications and how they work. Then, I have listed code samples to create, read and remove cookies in PHP with brief description of each. Its written in right flow, first things are explained first. And no need to read in one sitting, take breaks but absorb as you read.

What are Cookies

Basically, a cookie is data in the form of key value pair (e.g. city=Lahore) that is stored in browser's temporary memory. Cookies are created at web browser on the instuction of web server. Once some cookies are created in web browser by a web application, when user send new requests to same web application, all existing cookies are automatically added in HTTP request by the web browser. So the data stored by web developer in user browsesr (in the form of cookies), automatically reaches back at server in new requests.

When web server send instruction to create a new cookie, it also send cookie expiry time to browser (or default time is used, explained later), which is used by browser to automaticaly remove the cookie from its memory. Once a cookie is removed, in subsequent requests, that cookie is no more sent to web server.

What Type of Data is Stored in Cookies

We (web developers) use cookies to store small amount of textual data in user's browser, temporarily. Cookies data is in key/value form. We can use this data to generate personalize response for user. Below I have explained two practical examples where we may use cookies.

Show Products of User Interest
If you are developing a ecommerce store that contains tens or hundreds of products' categories. When user visit some specific categories pages, you can stored those categories (names or IDs) in user browser in the form of cookies. When user visit your online store next time (after some days or months), browser would automatically send the cookies you stored (list of categories, in this case) to server, where we can read them to show top selling products of those categories only. If you should products of user interest at home page, there is more chance of user visting those products detail pages, hence potentially leading to more sales. So by using cookies, you may personaliz your website for each user.

Automatic Login
We may use cookies for automatic login the user into our web application. You must have seen this at Facebook, Youtube and Gmail etc. You login there once and choose "Remember Me" option, when you visit the website again, you are logged-in automatically. How we can do this? When user login first time in our web application, we add some user identify information (for example, a random alphanumeric string generated against that user) in user browser via cookie. When user visit our website again, that cookie is automatically send to server by browser, we can use that cookie value to decide for which user it was generated, and forward him to logged-in user dashboard, and not to login page.

I hope, you got the idea, for what type of use cases, the cookies are best fit to use.

How to Create Cookies in PHP

Above I explained, what are cookies and for what purpose they are best fit. Now, I explain how exaclty a web browser know when it should create a new cookie and when it should remove the cookie from browser memory?

To understand cookies detail, you must have basic idea of how HTTP request/response work. When user open a URL, web browser create an HTTP request packet and send it to server using TCP connection or socket. When server receive an HTTP request, it creates an HTTP response packet and send it to web browser. HTTP packets has two parts (like other protocols) i.e. headers and payload. The headers carry mostly meta data e.g. user browser version, operatin system, server info, payload size, payload content type, and others. Basically, there are different type of headers, each serve a specific purpose, for example, Location header serve as instruction to browser to load another page automatically, called redirect. Cache-control header contains information whether the contents shall be cached by browser or not. The payload part of HTTP packet carries actual packet data e.g. HTML, CSS, etc. in HTTP response or form input fields data in case of HTTP Request e.g. when you submit form using POST. Sometimes, the payload may be empty, for example, when user opens a URL by typing in address bar or submit the form using GET.

How a cookie is created? When user request a page that contain an instruction to create new cookie, server adds Set-Cookie header in HTTP response, when browser receive Set-Cookie header, it creates a new cookie using information found in Set-Cookie header. For example, below page, create-cookie.php call setcookie function to create new cookie.

<!DOCTYPE HTML>

<html>
<head>
    <title>Create New Cookie</title>
</head>
<body>

<h3> Create New Cookie</h3>
<?php
    setcookie("city", "Lahore");
?>

</body>
</html>

setcookie PHP function called in above code adds Set-Cookie header in HTTP response. For simplicity, I have added no other content to web page, you may add more HTML/CSS in page, these contents has nothing to do with cookies.

Below figure shows above code output. If you open Developer Tools plugin using Ctrl+Shift+I and open Network tab before sending the request, it shall display HTTP headers of request and response packet, when you would send the request. You see, in response headers, Set-Cookie header is there, it contains the cookie name and value we defined in above code sample.


When web browser find Set-Cookie: city=Lahore header in HTTP response, it create a new cookie with name city and value Lahore . The Set-Cookie is an HTTP response header because its found only in HTTP response packets. By default, city cookie shall remain in browser until user keep interacting with our web application, when user will close the browser, the cookie would be removed. I would shortly explain how we can instruct the browser to remove cookies as per our requirement. Lets first look at how to get cookies data at server in subsequent requests.

How to Get Cookies at Web Server in PHP

Once web application has saved some cookies in web browser. When user send new requests to same web application, browser automatically add all cookies saved by that web application in each web request. At server side, before passing request processing flow to our web page, the server automatically creates $_COOKIE array and initialize the array using cookies received from browser. The cookie name becomes key of associative array and cookie value become the value against that key in the array. If you are familiar with PHP arrays, getting data from $_COOKIE array is easy, you just pass the key to this associative array, you get the corresponding value. Below get-cookie.php print the cookie value on web page, that is displayed to user:

<!DOCTYPE HTML>
<html>
<head>
    <title>Get Cookie</title>
</head>
<body>
<h3>Get Cookie</h3>

<?php
if (isset($_COOKIE["city"]))
    echo $_COOKIE['city'];
?>

</body>
</html>

It is good practice to use isset function, because if this page is accessed directly (without creating the cookie) or user cleaned browser temporary memory, no cookie would come from user, reading the city key from $_COOKIE array would break the code. So, its good practice to frist check an index, before we read it.

Below is the output of above code:


When user send request to server, all cookies saved by web application are put into an HTTP header whose name is Cookie. Cookie is a request header because it exist only in HTTP requests. Browser add this header in request only if there are some cookies the browser want to send to web server. If no cookies were saved by the web application earlier, there would be no Cookie header in HTTP request. In above figure, I have highlighted the Cookie header in red, you see, the header is shown under Request Headers which shows when get-cookie.php page was fetched, this header was sent to web server. Web server used this header to initialize $_COOKIE array that we used earlier to read cookie value.

How to Remove Cookies Setting Expiry Time in PHP 

We can set an expirary time when creating a new cookie. That expirary time is also sent to browser and saved with cookie key/value. When that expiry time reaches, cookie is automatically removed by web browser. When a cookie has expired, its no more sent to server in new requests (as it do not exist any more). Here is the code that adds same cookie but also set an expirary time:

<!DOCTYPE HTML>

<html>
<head>
    <title>Create New Cookie</title>
</head>
<body>

<h3> Create New Cookie</h3>

<?php
    setcookie("city", "Lahore", time() + 60);
?>

</body>
</html>

The last parameter passed to setcookie function is the time in seconds when we want the cookie to expire. The time() function return time in seconds since the January 1 1970 00:00:00 GMT we can add some seconds to make it a future time. In above code, I have added 60 seconds, thats means I want cookie to expire after 60 seconds.

When expirary time is set, the Set-Cookie header not only contains the cookie key/value but also the expiry time. Here are the contents of Set-Cookie header that goes from web server to web browser as result of executing above code i.e. create-cookie-with-expiry.php:


I fetched page page at 11:38:26. The expiry time was 60 seconds, so the web server set the expires value to 1 minute ahead from when the setcookie was called. It also added Max-Age=60 parameter, that shows the cookie should reside in browser only for 60 seconds, after that, browser should remove it.

If you fetch the get-cookie.php page after 1 minute, you would notice, browser do not send city cookie to server because the city cookie has expired. Here is output when we call get-cookie.php after the cookie has expired:


You see, there is no Cookie header in Request Headers section of the HTTP request packet. The isset function used in get-cookie.php returned false (see get-cookie.php code given above), rhats why, the web server has not printed the city value on web page, as the city key was not found in $_COOKIE array.

How to Remove Previously Added Cookie in PHP

In last code sample, we defined expiry time while creating a new cookie i.e. when setcookie function was called. Sometime, for some reason, we may need to remove a cookie from web browser whose expirary time has not reached yet or a cookie for which the expiry time was not set initially (the default expiry time is the duration of user session with web server, when the user close the browser, the cookies for which we do not set an expiry time are removed).

Lets assume, a city cookie was created with expiry time of 2 weeks but we want to delete it immediately when user call remove-cookie.php. This is just an example, we usually delete cookies from some application sates e.g. user logout, user changed some preference, etc. There are multiple ways to remove such cookies, below I have listed 2 methods to remove:

Method 1. Set the existing cookie value to empty string. When Set-Cookie header reaches at browser with empty string value, browser would not create the cookie, if a cookie with same key found, browser would remove it too. See below remove-cookie-1.php

<!DOCTYPE HTML>
<html>
<head>
    <title>Remove Cookie</title>
</head>
<body>

<h3>Remove Cookie</h3>

<?php
if (isset($_COOKIE["city"])) {
    setcookie("city", "");
    echo "city cookie removed";
}
?>

</body>
</html>

isset is used to make sure cookie exist already i.e. it came in current request packet. If cookie do not exist already, then it do not make sense to delete it.

Method 2: Cookie can be removed by setting it expiry time to current or past time. Yes, if you create a new cookie with negative expiray time or current time, when the Set-Cookie headers reach at browser. Browser would remove the cookie if a cookie of same name already exist. Below is the remove-cookie-2.php code:

<!DOCTYPE HTML>
<html>
<head>
    <title>Remove Cookie</title>
</head>
<body>

<h3>Remove Cookie</h3>

<?php
if (isset($_COOKIE["city"])) {
    setcookie("city", "Value does not matter", time() - 10);
    echo "city cookie removed";
}
?>

</body>
</html>

When the above page is fetched, it shows below output. I have also displaed the Set-Cookie heaer, you can see the Max-Age is set to -10. When browser receive an HTTP packet in which max-age negative. It do not create the cookie, if it already exist, browser remove that cookie too.


While calling setcookie function, if you do not add or subtract anything from time(), max-age value would be 0, it also means, the browser would remove the cookie. When you remove a cookie using egatice or zero max-time, it does not matter what value you set for that cookie. You may leave it empty or set some random text.

~
Consider leaving your feedback below if you found it helpful to understand cookies basics or where it can be improved further.

Comments

  1. Excellent, it covers all concept of Cookies that I want to understand.

    ReplyDelete
  2. The best blog that I have ever seen till now with useful content, thanks for sharing do keep updating...
    Best Online Software Training Institute | PHP Training

    ReplyDelete

Post a Comment