PHP Cookies | Create,Access,Modfiy and delete

PHP Cookies | Create,Access,Modfiy and delete

Create Cookies in PHP

PHP provides an inbuilt function setcookie(), that can send an appropriate HTTP header to create the cookie on the browser.

While creating the cookie, we have to pass require arguments with it.

The only a name argument is a must but it is better to pass value, expires, and path to avoid any ambiguity.

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


<?php
$cname="username";
$cval="shivam";
setcookie($cname,$cval,time()+(86400*30),"/");
if(!isset($_COOKIE[$cname]))
{
 echo $cname."Not Set";
}
else
{
 echo "Set, value is ",$_COOKIE[$cname];
}
?>
Output:

Modify Cookies Value in PHP

Cookie value can be retrieved using global variable $_COOKIE

We use the isset() function to find out if the cookie is set or not.

Modification of the cookie can simply be done again by setting the cookie using the setcookie() function.


The modified cookie can be checked by calling the same cookie with its name to check its modified value.

Delete Cookies in PHP

The cookie can be deleted from the user browser simply by setting expires argument to any past date it will automatically delete the cookie from the user browser.

A deleted cookie can be checked by calling the same cookie with its name to check if it exists or not.

<?
setcookie("USer","",time()-3600);
echo "Cookie user is deleted";
?>
Output:


Accessing Cookies Value in PHP

For accessing a cookie value, the PHP _COOKIE superglobal variable is used. It is an associative array that contains a record of all the cookies values sent by the browser in the current request. The records are stored as a list where cookie name is used as the key

Syntax:

$Value=COOKIE("CookieName"://returns cookie value

<?
setcookie("User","Shivam")
?>
<!DOCTYPE html>
<html>
<head>
 <title>cwipedia.in</title>
</head>
<body>
<?
if(isset($_COOKIE['User']))
{
 echo "Set The value is ",$_COOKIE['User'];
}
else
{
 echo "Cookie is not found";
}
?>
</body>
</html>

Output:

Comments