blog

Home / DeveloperSection / Blogs / What is a cookie?

What is a cookie?

zack mathews 1649 07-Jun-2016

A Cookie is a text file that the server embeds on the user’s computer. A cookie is used to identify a user. These cookies are also used for tracking purpose.PHP supports HTTP cookies. These cookies are usually set in HTTP header. With the help of PHP you can create and delete the cookie.

Create a cookie with PHP

setcookie() function is used to create a cookie. This function has six parameters:

Name: This parameter is the name of the cookie and store in environment variable called HTTP_COOKIE_VARS.

Value: It is used to store the content of the cookie.

Expiry: If this parameter is not set than cookie will automatically expire when the browser is closed.

Path: This parameter specifies the directories for which cookie is valid.

Domain: All cookies are valid for only those host and domain, who had created them.

Security: This can be set to 1 to specify the secure transmission using HTTPS otherwise set 0 for cookie to be sent by regular HTTP.

Syntax:
setcookie(name, value, expire, path, domain, secure)

 

<?php
   setcookie("name", "Neha singh", time()+3600, "/","", 0);
   setcookie("salary", "35000", time()+3600, "/", "", 0);
   echo "Set Cookies"
?>
Output:
Set Cookies
 Modify a cookie

To modify a cookie use the same name and function setcookie():  

<?php

setcookie("name","Raghu raj");//Neha singh is replaced by Raghu raj.
if(!isset($_COOKIE["user"]))
{
echo "Cookie is not set.";
}
else
{
echo "Cookie is set.";
}
?>
Output:
Cookie is set. 

Delete a cookie

To delete a cookie use setcookie() function with expiration time:

<?php

// set the expiration date to one hour ago
setcookie("name", "", time() - 3600);//name cookie will be deleted
echo "Cookie 'name' is deleted.";
?>

 

Output: 
Cookie 'name' is deleted.

 


Updated 15-Mar-2018

Leave Comment

Comments

Liked By