In this lesson, you will learn about HTTP cookies in PHP.

An HTTP cookie refers to the small piece of data sent by the web server to the user’s web browser. The browser may save it and sent it back to the web server with the next request sent. It can contain up to 4KB of data.

Cookies in PHP

Cookies are limited to their domain only which means a site can only access cookies it has set itself and not the other cookies. In most web browsers you can reserve up to 20 cookies per domain.

The data stored in a cookie is in the form of one or more name-value pairs which can be encrypted to add an extra layer of security.

Why you need Cookie?

Mostly cookies are used to manage user sessions over a span of time or to store user’s preferences, personal identification information, etc.

HTTP 1.0 is a stateless protocol which means it cannot differentiate between multiple web requests whether these requests are coming from the same user or different users are making those web requests.

For example, you have to create a sign in page that remembers the user being signed-in for 2-weeks, if he chooses to click on remember me checkbox at the time he logs in. To implement this feature, you need to create a cookie which holds user’s information for 2-weeks. If the user returns within the 14-days, the web application should take the user directly to its dashboard. But if he returns after 2-weeks, the app should ask him to login again.

Web browsers store cookies in the form of text files which can be easily viewed by anyone who has access to user’s computer. It is not safe to store sensitive information like user name or password in a cookie. Plus, if the user uses the same password for more than one website, then the user’s personal credentials can be compromised on other apps as well.

Creating Cookies in PHP

PHP has built-in support for cookies. You can create a cookie using the setcookie() function. Cookies are sent as a part of HTTP header so it should be sent before the body to avoid headers already sent error.

Syntax of cookies in PHP

setcookie ( string $name [, string $value = "" [, int $expires = 0 [, string $path = "" [, string $domain = "" [, bool $secure = FALSE [, bool $httponly = FALSE ]]]]]] ) : bool

$name – To access a cookie, you are going to call it using its name.
$value – This will store the small piece of data for user’s persistence or tracking.
$expires – This argument sets the expiry date of the cookie. The format to set the expiry time is to use the time() function plus the number of seconds before you wish the cookie to expire.

For example, the following code will create a cookie that will expire after an hour.

setcookie("fav-color", "pink", time()+3600);

1-hour is equal to 3600 seconds. To set the expiry time for 24 hours, use time()+(3600*24) instead.

Setting expiry time of the cookie to zero will delete the cookie when the web browser is closed. These are also known as session cookies.

$path – It stores the path of the web server. If set as ‘/’, the cookie will be accessible throughout a domain.

$domain – It stores the domain name where the cookie will be returned.

$secure – If set as true, the cookie will be sent over a secured HTTP connection. The default value is set as false.

PHP lets you access cookie(s) using $_COOKIE array.

For example, the following code will store and print the user’s information.

<?php

setcookie("Gender", "Male");
setcookie("Name", "John");
setcookie("Age", "40");
setcookie("Status", "Married");

?>

Use print_r() function to print the $_COOKIE array

<?php
echo "<pre>";
print_r($_COOKIE);
echo "</pre>";
?>

Reading PHP cookie values

Retrieving cookie’s values in PHP is really simple. Once the web server has set the cookie, you can read its value using the superglobal associate array $_COOKIE. PHP provides isset() function which lets you check if the particular cookie exists or not.

<?php
If(!isset($_COOKIE['username'])){
setcookie("username", "Admin");
}
echo $_COOKIE['username'];
?>

Deleting PHP cookies

If you no longer need a cookie, you can delete the cookie by using the unset() function or by setting the empty value for a cookie. You can also delete the cookie by setting expiry date in the past.

<?php
if(isset($_COOKIE['first_name'])){
setcookie('first_name','', time()-3600);
}
?>

Updating PHP cookies

To update the values of a cookie, simply update the value of the cookie by using an assignment operator.

<?php
if(isset($_COOKIE['name']))
$_COOKIE['name'] = "John";
?>

Example

<?php
$visitor_count = 0;
if(isset($_COOKIE['count'])){
$visitor_count = $_COOKIE['count'];
$visitor_count++;
}
if(isset($_COOKIE['last_visit'])){
$last_visit = $_COOKIE['last_visit'];
}
setcookie('count', $visitor_count);
setcookie('last_visit', date("H:i:s"));
if($visitor_count == 0){
echo "Welcome! ";
} else {
echo "This is your visit number ". $visitor_count;
echo "<br>We are glad to see you again ";
echo "<br>Last time, you were here at ".$last_visit;
}
?>

 

PHP Functions Tutorial Home PHP Sessions
Last modified: April 17, 2019