cookie-banner

Cookie in PHP Language

What is Cookie ?

A Cookie is small pieces of data that a website stores on our computer either in the memory of our computer or other devices such as mobile phones, tablet devices etc.

Why we use Cookie ?

There are various reasons for a website to use it. This will include the security for logging in the website or remember the name of the user, etc. In short, The main use of cookies is to identify the user. Cookies are stored on the user’s computer. Whenever The user requests a page using a browser, it will send the cookie with the request. So we can say that it is used on a client side. The setcookie() function is used to create a cookie in PHP.

Syntax :

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

Note : Only the name parameter is required. All other parameters are optional.

name(string) : Name of the cookie.

value(string) : Value of the cookie. This value is stored in the client computer. Do not store any important data in it because we can see the stored value in the browser. For sensitive data, the session should be the best option.

expire(int) : This is the time when it will expire automatically and after that, we are not able to get the same value for it.

path(string) : You can set the specific path for it. i.e if you do not want to create the cookie for the whole site and you just want that on a single page then you can do this by using this parameter.

domain(string) : You can create it for a specific domain.

secure(bool) : This will indicate that the cookie should only transmit if the client has a secure HTTPS connection. If we set the value “true” for this parameter then it will be stored for only the secured HTTPS connection.

HTTPonly(bool) : When we set this parameter as true, it will be available for HTTP Protocol only and It can not be accessible for scripting language i.e Java-script. This will secure our site from some hacking script.

Note: The expire parameter takes on a Unix time stamp, the date format “DD-Mon-YYYY HH:MM:SS GMT”, this is because PHP automatically does this conversion internally on client’s computer.

Create and Retrieve Cookie :

Following is the example which will create a cookie named “fruit” with the value “Apple”. It will expire after 2 days (86400 * 2). The “/” means that it is available on the whole website (otherwise, you can also select the directory you prefer). The time() function will return the current time in the number of seconds.

Note: The setcookie() function must be placed BEFORE the <html> tag.

To retrieve the cookie value we will use the global variable called $_COOKIE. At the time of retrieving a value, we will use an empty() function which will save us from throwing notice for an undefined variable.

<?php
setcookie("fruit", "Apple", time() + (86400 * 2), "/"); // 86400 = 1 day
?> 
 
<html>
<body>
 
<?php
if(empty($_COOKIE["fruit"])) {
    echo "Cookie named '" . $_COOKIE["fruit"] . "' is not set!";
} else {
    echo "Cookie Fruit is set!<br>";
    echo "Value is: " . $_COOKIE["fruit"];
}
?>
 
</body>
</html>

Note: Value of the Cookie is automatically URL-encoded when sending the cookie, and automatically decoded when received.

Where can you see Cookie in your browser?

If you are chrome user then right click on your screen. Select, Inspect from the menu. You will find the options like below. Now  select the Resources->Cookies->localhost from the tab that we opened using inspect.

cookie-blank-console

In the above image, we can see, there are some default, cookies which are set by the browser. Now run the file with the above mention code.

cookie-console

In the above image, we have an output like “Cookie named ” is not set!” this is because when we run the code first time we are not able to find the value is set “fruit” in our computer. So it will display the message like that. Now please refresh your page again we will get the message like below.

Output :

Cookie Fruit is set!
Value is: Apple

Modify the value of Cookie :

To modify the value, we just need to reset it by setcookie() with a new value.

<?php
setcookie("fruit", "Banana", time() + (86400 * 2), "/"); // 86400 = 1 day
?> 
 
<html>
<body>
 
<?php
if(empty($_COOKIE["fruit"])) {
    echo "Cookie named '" . $_COOKIE["fruit"] . "' is not set!";
} else {
    echo "Cookie Fruit is set!<br>";
    echo "Value is: " . $_COOKIE["fruit"];
}
?>
 
</body>
</html>

Now refresh your page two times and check the output. It should be like below. On the first refresh, it will set the new value “banana” for cookie “fruit” in your browser and second refresh, it will show you the new value for it.

Output :

Cookie Fruit is set!
Value is: Banana

Remove Cookie :

To remove cookie using PHP from your computer, you just need to set “expire” parameter in past like below.

<?php
// set the expiration date to one hour ago
setcookie("fruit", "", time() - 3600);
?>
<html>
<body>
 
<?php
echo "Cookie 'fruit' is deleted.";
?>
 
</body>
</html>
 
Output : 
 
Cookie 'fruit' is deleted.

Remove it Manually :

To remove it manually from your computer please check-out the below image.

cookie-remove

Note : It's advisable to use the session for sensitive data, i.e stores some information about a user while paying.

How to create URL specific Cookie?

<?php
setcookie("fruit", "Banana", time() + (86400 * 2), "/cookie.php"); // 86400 = 1 day
?>

The above code will create a "fruit" cookie for "/cookie.php". We will not get this value in another PHP file then cookie.php. To understand it properly create one file called testcookie.php. Write the below code in that file and try to access the fruit value.

<?php
if(empty($_COOKIE["fruit"])) {
    echo "Cookie named '" . $_COOKIE["fruit"] . "' is not set!";
} else {
    echo "Cookie Fruit is set!<br>";
    echo "Value is: " . $_COOKIE["fruit"];
}
?>

Now run this file in your browser. we will get the output like below.

Output :

A cookie named '' is not set!

Note : This kind of value cannot accessible outside of that specific URL.

Locations of Windows where Cookies folders reside :

following address in Windows 7:

  • C:\Users\username\AppData\Roaming\Microsoft\Windows\Cookies
  • C:\Users\username\AppData\Roaming\Microsoft\Windows\Cookies\Low

In Windows 8 and Windows 8.1, the Cookies are stored in this folder:

  • C:\Users\username\AppData\Local\Microsoft\Windows\INetCookies

What is include() in PHP ? To understand this in detail click here.

3 thoughts on “Cookie in PHP Language

Leave a Reply