SESSIONS COOKIES in PHP
SESSIONS COOKIES in PHP
setcookie() function:
• setcookie() function is used to set/create cookie.
Syntax: setcookie(name, value, expire);
• Only the name parameter is required. All other parameters are
optional.
Example:
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 seco
nds)
$_COOKIE Variable:
• $_COOKIE superglobal variable is used to get cookie.
i.e Once cookie is set, we can access cookie by
$_COOKIE superglobal variable.
Example:
$value=$_COOKIE["CookieName"];//returns cookie value
Example:
<?php
setcookie("user", "madhu");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>
Output:
Sorry, cookie is not found!
• Firstly cookie is not set. But, if you refresh the page, you will see
cookie is set now.
Output: Cookie Value: madhu