You might have heard about cookies, but what exactly are they and what can we actually do with them? In this tutorial, we will focus on the basics of cookies, and learn about their functionality in various web applications and site environments. We will also learn how to work with cookies in PHP.
Cookies vs Session Variables
Not sure if you need cookies or session variables? Session variables are a way to store data about a user in a database and to retrieve it later. Cookies are a way to store data about a user on the user’s computer. Session variables are typically used in applications that need to keep track of a user’s activity. Cookies are typically used in applications that need to store information about a user for a single site.
You can learn also learn about session variables in my post on using session variables in PHP.
What Is a Cookie?
Let’s start with the definition:
An HTTP cookie (also called web cookie, Internet cookie, browser cookie, or simply cookie) is a small piece of data stored on the user’s computer by the web browser while browsing a website.
We can think of cookies as text files, which are saved to your computer. When you request any web page, a web server sends the response of that web page to your browser. Along with the response, a web server could also send Set-Cookie
HTTP headers that request your browser to create cookie files on your computer. Once cookies are created for a website, a web server can read and write content from and to these files subsequently.
Cookies have an expiration date along with the cookie data. This date is set so that a browser can delete old cookies when they are no longer needed by a web server. If the expiration date is empty, the cookie will be deleted when the connection with the server is closed. This occurs when the site’s window or tab is closed by the user, or when the user closes the entire browser. These cookies, sometimes called session cookies, are mostly used for storing temporary settings.
Let’s quickly see how the Set-cookie
HTTP header looks like with the following example:
Set-Cookie: LastVisitedSection=CodeTutsplus; expires=Fri, 31-Mar-2021 23:59:59 GMT; path=/; domain=.tutsplus.com
In the above example, a web server asks the browser to create the LastVisitedSection
cookie. The browser would store CodeTutsplus
as the cookie data. A cookie file can store a text string or a number up to 4KB in size.
The expires attribute is used to specify the expiration date. And thus, the LastVisitedSection
cookie will be deleted from your computer after the 31-Mar-2021 23:59:59 GMT
date: March 31, 2021 at midnight.
The domain attribute is used to specify the domain in which the cookie will be active. If the domain is ads.google.com
, the cookie will only be sent to the server of that domain, and if the domain is .google.com
, the cookie will be sent to any server of any of the subdomains of Google, including google.com
itself. In our example, the LastVisitedSection
cookie will be available to tutsplus.com
and any of the subdomains of tutsplus.com
as well.
The path is the path of the domain to which the cookie is sent. This means that, if the path is set to /images/
, and the domain is set to ads.google.com
, the cookie will only be sent to the server if the browser requests a file from ads.google.com/images/
. If the path is set to /
, the cookie will be sent to the server regardless of the location of the requested file on the server. In our example, the LastVisitedSection
cookie will be sent to all pages of the tutsplus.com
domain.
So that’s how a web server creates cookies on your computer. In the next section, we’ll discuss the purpose of cookies.
What is the Purpose of Cookies?
The HTTP protocol is a stateless protocol, which means that there’s no built-in way a server can remember a specific user between multiple requests. For example, when you access a web page, the server is just responsible for providing the contents of the requested page. When you access other pages of the same website, the web server interprets each and every request separately, as if they were unrelated to one another. There’s no way for the server to know that each request originated from the same user.
Now, if you want to implement features like user login or shopping carts, you’ll need to identify if two requests came from the same browser. This is not possible with a stateless protocol. We need to maintain state or session between requests that are made by a browser to identify a user. That’s where cookies come to the rescue!
Cookies allow you to share information across the different pages of a single site or app—thus they helps maintain state. This lets the server know that all requests originate from the same user, thus allowing the site to display user-specific information and preferences.
The following diagram depicts how the HTTP protocol works with cookies.
How to Create Cookies in PHP
In this section, we’ll discuss how you can create cookies in PHP.
To create cookies in PHP, you need to use the setcookie
function. Let’s have a look at the basic syntax which is used to create a cookie.
setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );
The argument list in the setcookie
function should look familiar to you as we’ve already discussed most of these parameters earlier in this article. However, there are two more arguments, $secure
and $httponly
, that are important to understand.
If you set the $secure
parameter to TRUE
, the cookie will only be created if a secure connection exists. The $httponly
parameter allows you to make cookies HTTP only, and thus it will be accessible only through the HTTP protocol. Cookies that are set as HTTP only won’t be accessible by scripting languages like JavaScript.
So that’s about the syntax, let’s have a look at a real-world example.
<?php setcookie("LastVisitedSection", "CodeTutsplus", time() + 3600, "/", "tutsplus.com", 1);
It would create the LastVisitedSection
cookie with the CodeTutsplus
value, and it would expire in an hour. The path argument is set to /
, so it would be sent to all pages of the tutsplus.com
domain.
Now, let’s have a look at the following example.
<?php setcookie("favCourse", "PHP", time() + 3600, "/courses/", "code.tutsplus.com", 1);
As we’ve set the path argument to /courses/
, the favCourse
cookie will be only sent if a browser requests pages from https://code.tutsplus.com/courses/
.
In this way, you can create cookies in PHP. The most important thing to remember, when creating a cookie in PHP, is that you must set all cookies before you send any data to the browser. Cookies belong in the header, so you should always initialize new cookies before any output. This includes echo
or print
commands, and the <html>
or <body>
tags.
How to Read Cookies in PHP
Reading cookies in PHP is straightforward. You need to use the $_COOKIE
superglobal variable to read available cookies. In fact, the $_COOKIE
variable is an array which contains all cookies.
Let’s have a look at the following snippet.
<?php if(isset($_COOKIE["LastVisitedSection"])){ echo "Recently visited section: " . $_COOKIE["LastVisitedSection"]; } else{ echo "Welcome guest! We encourage you to explore different sections!"; }
You can use the print_r
or var_dump
function to check all available cookies for debugging purposes.
<?php print_r($_COOKIE);
It’s that easy to read cookies in PHP!
In the next section, we’ll see how to delete cookies.
How to Delete Cookies in PHP
It would be interesting for you to know that you can use the setcookie
function to delete cookies as well. The catch is that you need to set the expiration date in the past and a cookie will be deleted.
Let’s see it in action in the following example.
<?php unset($_COOKIE['LastVisitedSection']); setcookie("LastVisitedSection", "", time() - 3600, "/");
As you can see, we’ve specified the expiration date in the past by setting it to time() - 3600
. It’s important to note that we’ve also used the unset
function to remove the LastVisitedSection
cookie from the $_COOKIE
superglobal variable to make sure that the LastVisitedSection
cookie is not accessible later in the code.
Best Practices for Using Cookies in PHP
To wrap up I would like to sum up some best practices:
- Never insert sensitive data into a cookie. A client could be browsing on a public computer, so don’t leave any personal information behind.
- Never trust data coming from cookies. Always filter strings and numbers! Client computers can change cookies at will, so an attacker could write malicious data to the cookie in order to do something you don’t want your service to do.
- Try to estimate how long the cookie should be valid, and set the expiration date accordingly. You don’t want to hog the client’s computer with old cookies which are set to expire in a hundred years.
- Always set the
secure
andhttponly
flags when possible. If your application doesn’t edit the cookies with JavaScript, enablehttponly
. If you always have an HTTPS connection, enablesecure
. This improves the data’s integrity and confidentiality.
Conclusion
Today, we discussed the basics of cookies and how to use them in PHP. A related topic is sessions and session variables. You can learn how to use session and session variables in PHP right here at Envato Tuts+!