PHP cookie is a small piece of information that is stored at the client's browser. It is used to recognize the user.
Cookie is created at the server-side and saved to the client browser. Each time when a client sends a request to the server, the cookie is embedded with the request. Such a way, a cookie can be received at the server-side.
In short, a cookie can be created, sent and received at the server end.
PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag. For each cookie this function has to be called separately.
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments −
A cookie is created with the setcookie() function.
setcookie(name, value, expire, path, domain, secure, httponly);
Note: PHP Cookie must be used before <html> tag.
PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can access it by $_COOKIE superglobal variable.
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
[, string $domainName [, bool $secure = false [, bool $httponly = false ]]]]]] )
setcookie("CookieName", "CookieValue");/* defining name and value only*/
setcookie("CookieName", "CookieValue", time()+1*60*60);//using expiry in 1 hour(1*60*60 seconds or 3600 seconds)
setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "easytolearning.com", 1);
PHP $_COOKIE superglobal variable is used to get cookie.
$value=$_COOKIE["CookieName"];//returns cookie value
File Name: cookie_name.php
<?php
setcookie("user", "Suhail");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>
Officially, to delete a cookie you should call setcookie() with the name argument only but this does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired −
<?php
setcookie( "user", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>
© 2024 Easy To Learning. All Rights Reserved | Design by Easy To Learning