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.
setcookie(name, value, expire, path, domain, secure)
setcookie("name", "Neha singh", time()+3600, "/","", 0);
setcookie("salary", "35000", time()+3600, "/", "", 0);
echo "Set Cookies"
Modify a cookie
To modify a cookie use the same name and function setcookie():
setcookie("name","Raghu raj");//Neha singh is replaced by Raghu raj.
echo "Cookie is not set.";
echo "Cookie is set.";
Cookie is set.
Delete a cookie
To delete a cookie use setcookie() function with expiration time:
// set the expiration date to one hour ago
setcookie("name", "", time() - 3600);//name cookie will be deleted
echo "Cookie 'name' is deleted.";
Cookie 'name' is deleted.