What are HTTP cookies how to handle them in PHP?

You might have heard about cookies, but what exactly are they, and what can we 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 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 also learn about session variables in my post on using session variables in PHP.

  • What are HTTP cookies how to handle them in PHP?
    What are HTTP cookies how to handle them in PHP?
    What are HTTP cookies how to handle them in PHP?

    How to Use Sessions and Session Variables in PHP

    What are HTTP cookies how to handle them in PHP?
    What are HTTP cookies how to handle them in PHP?
    What are HTTP cookies how to handle them in PHP?

    Sajal Soni

    16 Feb 2021

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

setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );
4 HTTP headers that request your browser to create cookie files on your computer. Once cookies are created for a website, a web server can subsequently read and write content from and to these files.

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 user closes the site's window or tab, 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 what the

setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );
5 HTTP header looks like with the following example:

1
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

setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );
6 cookie. The browser would store
setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );
7 as the cookie data. A cookie file can store a text string or a number up to 4KB in size.

The

setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );
8 attribute is used to specify the expiration date. And thus, the
setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );
6 cookie will be deleted from your computer after the
1
0 date: 31 March 2021 at midnight.

The domain attribute is used to specify the domain in which the cookie will be active. If the domain is

1
1, the cookie will only be sent to the server of that domain, and if the domain is
1
2, the cookie will be sent to any server of any of the subdomains of Google, including
1
3 itself. In our example, the
setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );
6 cookie will be available to
1
5 and any of the subdomains of
1
5 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

1
7, and the domain is set to
1
1, the cookie will only be sent to the server if the browser requests a file from
1
9. If the path is set to
<?php
0, the cookie will be sent to the server regardless of the location of the requested file on the server. In our example, the
setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );
6 cookie will be sent to all pages of the
1
5 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 help 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.

What are HTTP cookies how to handle them in PHP?
What are HTTP cookies how to handle them in PHP?
What are HTTP cookies how to handle them in PHP?

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

<?php
3 function. Let’s have a look at the basic syntax which is used to create a cookie.

1
setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );

The argument list in the

<?php
3 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,
<?php
5 and
<?php
6, that are important to understand.

If you set the

<?php
5 parameter to
<?php
8, the cookie will only be created if a secure connection exists. The
<?php
6 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 it for the syntax—let’s have a look at a real-world example.

1
<?php
2
setcookie("LastVisitedSection", "CodeTutsplus", time() + 3600, "/", "tutsplus.com", 1);

It would create the

setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );
6 cookie with the
setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );
7 value, and it would expire in an hour. The path argument is set to
<?php
0, so it would be sent to all pages of the
1
5 domain.

Now, let’s have a look at the following example.

1
<?php
2
Set-Cookie: LastVisitedSection=CodeTutsplus; expires=Fri, 31-Mar-2021 23:59:59 GMT; path=/; domain=.tutsplus.com
1

As we’ve set the path argument to

2
4, the
2
5 cookie will be only sent if a browser requests pages from
2
6.

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

2
7 or
2
8 commands, and the
2
9 or
setcookie("LastVisitedSection", "CodeTutsplus", time() + 3600, "/", "tutsplus.com", 1);
0 tags.

How to Read Cookies in PHP

Reading cookies in PHP is straightforward. You need to use the

setcookie("LastVisitedSection", "CodeTutsplus", time() + 3600, "/", "tutsplus.com", 1);
1 superglobal variable to read available cookies. In fact, the
setcookie("LastVisitedSection", "CodeTutsplus", time() + 3600, "/", "tutsplus.com", 1);
1 variable is an array which contains all cookies.

Let’s have a look at the following snippet.

1
<?php
2
Set-Cookie: LastVisitedSection=CodeTutsplus; expires=Fri, 31-Mar-2021 23:59:59 GMT; path=/; domain=.tutsplus.com
5
Set-Cookie: LastVisitedSection=CodeTutsplus; expires=Fri, 31-Mar-2021 23:59:59 GMT; path=/; domain=.tutsplus.com
6
Set-Cookie: LastVisitedSection=CodeTutsplus; expires=Fri, 31-Mar-2021 23:59:59 GMT; path=/; domain=.tutsplus.com
7
Set-Cookie: LastVisitedSection=CodeTutsplus; expires=Fri, 31-Mar-2021 23:59:59 GMT; path=/; domain=.tutsplus.com
8
Set-Cookie: LastVisitedSection=CodeTutsplus; expires=Fri, 31-Mar-2021 23:59:59 GMT; path=/; domain=.tutsplus.com
9
1
0
1
1
1
2
1
3

You can use the

setcookie("LastVisitedSection", "CodeTutsplus", time() + 3600, "/", "tutsplus.com", 1);
3 or
setcookie("LastVisitedSection", "CodeTutsplus", time() + 3600, "/", "tutsplus.com", 1);
4 function to check all available cookies for debugging purposes.

1
<?php
2
1
7

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

<?php
3 function to delete cookies as well. The catch is that you need to set the expiration date in the past, and a cookie will then be deleted.

Let’s see it in action in the following example.

1
<?php
2
setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );
1
Set-Cookie: LastVisitedSection=CodeTutsplus; expires=Fri, 31-Mar-2021 23:59:59 GMT; path=/; domain=.tutsplus.com
6
setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );
3

As you can see, we’ve specified the expiration date in the past by setting it to

setcookie("LastVisitedSection", "CodeTutsplus", time() + 3600, "/", "tutsplus.com", 1);
6. It’s important to note that we’ve also used the
setcookie("LastVisitedSection", "CodeTutsplus", time() + 3600, "/", "tutsplus.com", 1);
7 function to remove the
setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );
6 cookie from the
setcookie("LastVisitedSection", "CodeTutsplus", time() + 3600, "/", "tutsplus.com", 1);
1 superglobal variable to make sure that the
setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false );
6 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
    1
    1 and
    1
    2 flags when possible. If your application doesn't edit the cookies with JavaScript, enable
    1
    2. If you always have an HTTPS connection, enable
    1
    1. 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 sessions and session variables in PHP right here at Envato Tuts+!

How to handle HTTP cookies in PHP?

Note: The setcookie() function must appear BEFORE the <html> tag. Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
What are HTTP Cookies? HTTP cookies, or internet cookies, are built specifically for Internet web browsers to track, personalize, and save information about each user's session. A “session” just refers to the time you spend on a site. Cookies are created to identify you when you visit a new website.

Can PHP deal with cookies?

PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() or setrawcookie() function.
An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to a user's web browser. The browser may store the cookie and send it back to the same server with later requests.