How can we handle cookies in php?

As a website developer, you can use PHP to set cookies that contain information about the visitors to your website. Cookies store information about a site visitor on the visitor's computer that can be accessed upon a return visit. One common use of cookies is to store an access token so the user doesn't need to log in each time he visits your website. Cookies can also store other information such as the user's name, the date of the last visit and shopping-cart contents.

Although cookies have been around for years and most people have them enabled, some users either do not accept them because of privacy concerns or automatically delete them when their browsing session closes. Because cookies can be removed by a user at any time and are stored in a plain-text format, don't use them to store anything sensitive.

In PHP, the setcookie() function defines a cookie. It's sent along with the other HTTP headers and transmits before the body of the HTML is parsed.

A cookie follows the syntax:

setcookie(name,value,expire,path,domain,secure,httponly);

where name​ denotes the name of the cookie and ​value​ describes the cookie's contents. ​For the setcookie() function, only the name​ parameter is required. All other parameters are optional. 

​To set a cookie named "UserVisit" in the visitor's browser that sets the value to the current date, and further sets the expiration to be in 30 days (2592000 = 60 seconds * 60 mins * 24 hours * 30 days), use the following PHP code:

<?php 
$Month = 2592000 + time();
//this adds 30 days to the current time
setcookie(UserVisit, date("F jS - g:i a"), $Month);
?>

Cookies must be sent before any HTML is sent to the page or they do not work, so the setcookie() function must appear before the <html> tag.

To retrieve a cookie from the user's computer upon the next visit, call it with the following code:

<?php
if(isset($_COOKIE['UserVisit']))
{
$last = $_COOKIE['UserVisit'];
echo "Welcome back! <br> You last visited on ". $last;
}
else
{
echo "Welcome to our site!";
}
?>

This code first checks if the cookie exists. If it does, it welcomes the user back and announces when the user last visited. If the user is new, it prints a generic welcome message.

TIP: If you are calling a cookie on the same page you plan to set one, retrieve it before you overwrite it.

To destroy a cookie, use setcookie() again but set the expiration date to be in the past:

<?php 
$past = time() - 10;
//this makes the time 10 seconds ago
setcookie(UserVisit, date("F jS - g:i a"), $past);
?>

​Optional Parameters

In addition to value and expire, the setcookie() function supports several other optional parameters:

  • Path​ identifies the server path of the cookie. If you set it to "/" then the cookie will be available to the entire domain. By default, the cookie works in the directory it's set in, but you can force it to work in other directories by specifying them with this parameter. This function cascades, so all subdirectories within a specified directory will also have access to the cookie.
  • Domain​ ​identifies the specific domain that the cookie works in. To make the cookie work on all subdomains, specify the top-level domain explicitly (e.g., "sample.com"). If you set the domain to "www.sample.com" then the cookie is only available in the www subdomain.
  • Secure​ specifies whether the cookie should transmit over a secure connection. If this value is set to TRUE then the cookie will set only for HTTPS connections. The default value is FALSE.
  • Httponly​, when set to TRUE, will only allow the cookie to be accessed by the HTTP protocol. By default, the value is FALSE. The benefit of setting the cookie to TRUE is that scripting languages cannot access the cookie. 

Last update on August 19 2022 21:50:39 (UTC/GMT +8 hours)

Cookies are used to store the information of a web page in a remote browser, so that when the same user comes back to that page, that information can be retrieved from the browser itself.

In this tutorial, we will discuss how to use Cookies in PHP. We have several examples in this tutorial which will help you to understand the concept and use of a cookie.

Uses of cookie

Cookies are often used to perform following tasks:

  • Session management: Cookies are widely used to manage user sessions. For example, when you use an online shopping cart, you keep adding items in the cart and finally when you checkout, all of those items are added to the list of items you have purchased. This can be achieved using cookies.
  •  
  • User identification: Once a user visits a webpage, using cookies, that user can be remembered. And later on, depending upon the search/visit pattern of the user, content which the user likely to be visited are served. A good example of this is 'Retargetting'. A concept used in online marketing, where depending upon the user's choice of content, advertisements of the relevant product, which the user may buy, are served.
  •  
  • Tracking / Analytics: Cookies are used to track the user. Which, in turn, is used to analyze and serve various kind of data of great value, like location, technologies (e.g. browser, OS) form where the user visited, how long (s)he stayed on various pages etc.

How to create a cookie in PHP

PHP has a setcookie() function to send a cookie. We will discuss this function in detail now.

Usage:


setcookie(name, value, expire, path, domain, secure, httponly)

Parameters:

setcookie() has several parameters. Following table discusses those.

ParameterDescriptionWhich type of data
name Name of the cookie. String
value Value of the cookie, stored in clients computer. String
expire Unix timestamp, i.e. number of seconds since January 1st, 1970 (called as Unix Epoch). Integer
path Server path in which the cookie will be available. String
domain To which domain the cookie is available. String
secure If set true, the cookie is available over a secure connection only. Boolean
httponly If set true, the cookie is available over HTTP protocol only. Scripting languages like JavaScript won't be able to access the cookie. Boolean

setcookie() returns boolean.

Example:

Following example shows how to create a cookie in PHP. Code first and then some explanation.

<?php
$cookie_value = "w3resource tutorials";
setcookie("w3resource", $cookie_value, time()+3600, "/home/your_usename/", "example.com", 1, 1);
if (isset($_COOKIE['cookie']))
echo $_COOKIE["w3resource"];
?>

So, what does the code above does? The first parameter sets the name of the cookie as 'w3resource', the second parameter sets the value as 'w3resource tutorials', the third parameter states that the cookie will be expired after 3600 seconds (note the way it has been declared, we use time() and then add the number of seconds we wish the cookie must be expired after), the fourth parameter sets path on the server '/home/your_name' where your_name may be an username, so it directs the home directory of a user, the fifth and sixth parameter is set to 1, i.e. true, so the cookie is available over secure connections only and it is available on HTTP protocol only.

echo $_COOKIE["w3resource"]; simply prints the cookie value. This way you can retrieve a cookie value.

Output:

w3resource tutorials

How to create a cookie without urlencoding the cookie value

The setcookie() sends a cookie by urlencoding the cookie value. If you want to send a cookie without urlencoding the cookie value, you have to use setrawcookie().

This function has all the parameters which setcookie() has, and the return value is also boolean.

PHP $_COOKIE autoglobal

If a cookie is successfully sent to you from the client, it is available in $_COOKIE, which is automatically global in PHP, if the variables_order directive in php.ini is set to C.

The following code shows how to use $_COOKIE.

<?php
$cookie_value = "w3resource tutorials";
setcookie("w3resource", $cookie_value, time()+3600, "/home/your_usename/", "example.com", 1, 1);
echo 'Hi ' . htmlspecialchars($_COOKIE["w3resource"]);
?>

If you wish to retreive all the cookies, you may use the following command

<?php
print_r($_COOKIE);
?>

headers already sent problem because of cookies

PHP Cookies are part of the HTTP header. Therefore, in a PHP script, if it is not set before any another output is sent to the browser, you will get a warning like "...headers already sent....".

To get rid of the problem, you may use "Output buffering functions". Following code shows how to add an output buffering function.

<?php
ob_start(); //at the begining of the php script
//your code goes here
//add these two lines at the end of the script
$stuff = ob_get_clean(); 
echo $stuff;
?>

How to delete a cookie

To delete a cookie value, you may set the expiry time of the cookie in the past. In the following code snippet, cookie expiry time is set one hour before.

<?php
$cookie_value = "w3resource tutorials";
setcookie("w3resource", $cookie_value, time()-3600, "/home/your_usename/", "example.com", 1, 1);
?>

Javascript cookies vs php cookies

This may confuse you if you are just starting out with web programming. But in practice, Cookies are defined by RFC 2965. It is a standard which can be used any programming language. It has nothing to do with PHP vs JavaScript. In PHP, as we have seen in the first example of this tutorial, that cookies can be set such a way that it can't be accessed by client side JavaScript, but that is a programming feature only.

Cookies vs Sessions

Both cookies and sessions are used for storing persistent data. But there are differences for sure.

Sessions are stored on server side. Cookies are on the client side.

Sessions are closed when the user closes his browser. For cookies, you can set time that when it will be expired.

Sessions are safe that cookies. Because, since stored on client's computer, there are ways to modify or manipulate cookies.

Hopefully, this tutorial about PHP cookies is useful for you. Let us know if you have questions or suggestions.

Previous: PHP File Upload
Next: XForms

How are cookies stored in PHP?

Cookies are always stored in the client. The path only sets restrictions to what remote pages can access said cookies. For example, if you set a cookie with the path "/foo/" then only pages in the directory "/foo/" and subdirectories of "/foo/" can read the cookie.

How do I enable 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 );

What are PHP cookies used for?

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. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser.

Can we destroy cookies in PHP?

Deleting Cookie: There is no special dedicated function provided in PHP to delete a cookie. All we have to do is to update the expire-time value of the cookie by setting it to a past time using the setcookie() function.