Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Anatomy of a Cookie
3.
Creating PHP Cookies
3.1.
PHP
4.
Accessing PHP Cookies
4.1.
PHP
5.
Modifying a Cookie
5.1.
PHP
6.
Deleting A PHP Cookie
6.1.
PHP
7.
How To Check If Cookies Are Enabled?
7.1.
PHP
8.
Frequently Asked Questions
8.1.
What is the maximum size a cookie file can have?
8.2.
How many cookies can a browser have?
8.3.
How many cookies in PHP?
8.4.
Where cookies are stored in PHP?
9.
Conclusion
Last Updated: Jul 17, 2024
Easy

PHP Cookie

Author Ranjul Arumadi
2 upvotes

Introduction

A cookie is a small text file stored on the user's computer. Cookies can only have a maximum size of 4096 bytes. These cookies are kept for tracking purposes and are used to identify a user. Every time when the same computer requests a page using a browser, a cookie will be sent along with it. We can create and retrieve cookie values with the help of PHP.

PHP Cookie

Cookies store small data like name, age, etc., on the local machine. The next time when the browser sends a request to the web server, it sends the cookie information to the server, identifying the user. This article will discuss creating and using PHP cookies in detail.

Anatomy of a Cookie

Cookies are usually appended in an HTTP header. Let us see how PHP sets the header for a cookie.

HTTP/1.1 200 OK
Date: Mon, 03 Feb 2003 22:07:41 GMT
Server: Apache/1.4.9 (UNIX) PHP/6.0b3
Set-Cookie: name=abc; expires=Saturday, 04-Feb-07 22:03:38 GMT;
                path=/; domain=codingninjas.com
Connection: close
Content-Type: text/html

 

The Set-Cookie header in the above code has a domain, name-value pair, a path, a GMT date. The name and value will have a URL encoding. The expires field instructs the browser to "forget" the cookie after a set time and date.
 

The information in the header will be stored in the browser until the expiry, provided the browser is configured for it. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. Let us look at what the browser's header will look like. 

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Firefox/4.6 (X11; I; Linux 2.2.6-15akmac ppc)
Host: pink.demon.co.in:5136
Accept: image/abc, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8759-1,*,utf-8
Cookie: name=abc

 

A PHP script will then access the cookie in the environmental variables $_COOKIE or $HTTP_COOKIE_VARS[], which holds all cookie names and values. The above cookie can be accessed using the $HTTP_COOKIE_VARS["name"].

Creating PHP Cookies

As mentioned before, we can both create and retrieve cookie values with PHP. To create a PHP cookie, we use the setcookie() function. This function can take up to six arguments as its parameters. The setcookie() function must be called before the <html> tag. The syntax for using the setcookie() is as follows:

setcookie(name, value, expire, path, domain, security);
You can also try this code with Online PHP Compiler
Run Code

 

The name parameter is required; all the other parameters are optional. The values are:

  • name - It is used to set the name of the cookie. We can use the name parameter to access the cookies. The name is stored in HTTP_COOKIE_VARS, which is an environment variable.
  • value - This parameter is used to set the value of the named variable. This is the actual content that we intend to store.
  • expire - This parameter specifies a future time when the cookie becomes inaccessible. If we do not set the value for this parameter, then the cookie will automatically expire when the web browser is closed.
  • path - This parameter specifies the directories for which the cookie is valid. If the path value is set as one forward slash symbol  ("/"), it permits the PHP cookie to be valid for all directories.
  • domain - This parameter specifies the domain name of the cookie. It should contain at least two periods to be valid. The cookies will be valid only for the host and domain which created them.
  • security - This parameter can have only either of the two values: 1 or 0. It can be set to 1 if the cookie should only be sent with secure transmission using HTTPS. By setting the security value to 0, we can send the cookie using regular HTTP.
  • httponly - If we set this optional parameter to TRUE, the cookie can only be accessed through the HTTP protocol. This setting can help us reduce identity theft through XSS attacks. The default value is FALSE.

 

Now let us see an example to understand this better:

  • PHP

PHP

<?php
setcookie("name", "Sam", time()+3600, "/","", 0);
setcookie("age", "20", time()+3600, "/", "", 0);
?>
<html>
<head>
<title>Example of Creating PHP Cookies</title>
</head>
<body>
<?php echo "We have set the PHP Cookies"?>
</body>
</html>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

output

Accessing PHP Cookies

We can access the PHP Cookies that we created in many ways. The easiest way is to use the variables $_COOKIE. Let us consider an example:

<html>  
<head>
     <title>Accessing PHP Cookies: Example</title>
 </head>
 <body>
     <?php
// Setting cookie
setcookie("name", "Sam", time()+3600, "/","", 0);
       echo $_COOKIE["name"]. "<br/>";
     ?>
 </body>
</html>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

output

 

To check if a cookie is set or not, we can use the isset()  function. We can see the usage of the isset() function with the help of the example.

  • PHP

PHP

<html>
<head>
<title>Accessing PHP Cookies: Example</title>
</head>
<body>
<?php

setcookie("name", "Sam", time()+3600, "/","", 0);

if( isset($_COOKIE["name"]))
echo "Hello " . $_COOKIE["name"] . "<br />";
else
echo "Cookies are not set" . "<br />";
if( isset($_COOKIE["age"]))
echo "Age: " . $_COOKIE["age"] . "<br />";
else
echo "Age cookies not set" . "<br />";
?>
</body>
</html>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

output

Modifying a Cookie

There will be times when we create a cookie, and later we might want to modify that cookie. To do this, we make use of the setcookie()  function. We can set the values of the PHP cookies again by using the setcookie() function.

 

Example:

  • PHP

PHP

<?php
$cookie_name = "name";
$cookie_value = "Sam";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<head>
<title>Modifying PHP Cookies: Example</title>
</head>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "The cookie '" . $cookie_name . "' is not set.";
} else {
echo "The cookie '" . $cookie_name . "' is set. <br>";
echo "The value of the cookie is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

output

Deleting A PHP Cookie

PHP provides us with a way to delete a cookie. To delete a PHP cookie, we have to modify the cookie using the setcookie() function and set the expiring time as an expired time.

  • PHP

PHP

<?PHP
// Setting the expiry time to one hour ago
setcookie("name", "Sam", time() - 3600);
?>
<html>
<body>
<?php
echo "The cookie is deleted.";
?>
</body>
</html>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

output

How To Check If Cookies Are Enabled?

To check if cookies are enabled, we first create a test cookie using setcookie() function, then we count the $_COOKIE array variable. 

  • PHP

PHP

<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "The cookies are enabled.";
} else {
echo "The cookies are disabled.";
}
?>
</body>
</html>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

output

Frequently Asked Questions

What is the maximum size a cookie file can have?

The maximum file size of the cookie depends on the browser. Cookies in the chrome browser can have a maximum size of 4096 bytes.

How many cookies can a browser have?

The number of cookies a browser can have depends on the browser. Chrome browser allows a maximum of 180 cookies.

How many cookies in PHP?

In PHP, there is no explicit limit on the number of cookies that can be set, but browsers typically restrict the number to around 20 cookies per domain, with a maximum size of 4KB per cookie.

Where cookies are stored in PHP?

In PHP, cookies are stored on the client's browser. They are sent by the server using the setcookie() function and stored as small text files on the user's device, then sent back to the server with subsequent requests.

Conclusion

Cookies are small text files used to store small data and identify the user. 

We discussed creating cookies, retrieving values from cookies, and deleting cookies using PHP. We can make cookies in PHP using the setcookie() function. We can access the cookies from PHP using the variable $_COOKIE. To check if a cookie is set or not, we can use the isset() function. 

 

We can modify the cookie details using the function setcookie(). To delete a cookie using PHP, we have to modify the cookie with the setcookie() function and set the expiration time as an expired time. We created a test cookie using the setcookie() function, and then we counted the $_COOKIE array variable to check if a cookie is enabled. 

If you loved reading this article about PHP cookies, check out :-

If you wish to enhance your skills in Data Structures and AlgorithmsCompetitive ProgrammingJavaScript, etc., you should check out our Guided path column at Code360

Live masterclass