Begin Web Programming with PHP & MySQL

Advertisements



PHP Cookie

A cookie stores information in a user's web browser. A cookie is a small file that the server embeds on the user's computer which then includes the cookies in future HTTP requests. Cookies inform websites about the user, enabling the websites to personalize the user experience.

Create Cookie with PHP

A cookie is created with setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Except the name parameter, all other parameters are optional. If the expiry of the cookie is set to 0 or omitted, the cookie will expire when the browser closes.

Eg:
<?php
$cookie_name = "user";
$cookie_value = "cookie today";
setcookie($cookie_name, $cookie_value, time() + 86400,"/"); // 86400 seconds = 1 day
if(isset($_COOKIE[$cookie_name]))
{
echo "Cookie value is: ".$_COOKIE[$cookie_name];
}
else
{
echo "Cookie is not set!<br>";
}
?>

Modify Cookies

We can modify a cookie value using setcookie() function, but we should add '/' as the path to prevent creating another cookie with the same name.

<?php
session_start();
$cookie_name = "user";
$cookie_value = "cookie now";
setcookie($cookie_name, $cookie_value, time() + 86400 * 2,"/"); // expiry in 2 days
if(isset($_COOKIE[$cookie_name]))
{
echo "New Cookie value is: ".$_COOKIE[$cookie_name];
}
else
{
echo "Cookie is not set!<br>";
}
?>

Delete Cookies

A clean way to delete a cookie is to clear both the $_COOKIE value and the browser cookie file.Use the setcookie() function with an expiration date in the past.
<?php
$cookie_name = "user";
$cookie_value = "cookie now";
setcookie($cookie_name, $cookie_value, time() + 8640,"/"); // expiry in a day
if (isset($cookie_name))
{
unset($_COOKIE[$cookie_name]); // unset cookie
setcookie($cookie_name, "", -1, '/'); // set cookie to a past time
}
if(isset($_COOKIE[$cookie_name]))
{
echo "<br>New Cookie value is: ".$_COOKIE[$cookie_name];
}
else
{
echo "<br>Cookie is not set!<br>";
}
?>