A cookie is a piece of information that is stored in the client browser. Additionally, a cookie is generated on the server and saved to the client browser.
The first time when a client sends a request to the server, the server embedded the cookie along with the response. Next time onwards client sends the request along with a cookie to the server. In such a way, cookies can be received on the server side.
A cookie is a small file that the server embeds on the user's computer. With PHP, we can both create and retrieve cookie values.
Note : Cookie must be used before html tag.☞ setcookie() function is used to set/create cookie.
Syntax:setcookie(name, value, expire);
In the above only the name parameter is required. All other parameters are optional.
Example1:setcookie("username","StudyGlance");
In the above example, defining a name and value for cookie
setcookie("username","StudyGlance",time()+1*60*60);
In the above example, defining a name and value for cookie along with expiry time (1 hour = 1*60*60 seconds or 3600 seconds)
☞ $_COOKIE superglobal variable is used to get/retrieve cookie. i.e Once cookie is set, we can access cookie by $_COOKIE superglobal variable.
Example:$value = $_COOKIE["username"];
A simple example to understand working with cookies in PHP.
<?php
// To create cookie
setcookie("username", "StudyGlance");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["username"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["username"];
}
?>
</body>
</html>
In the above example program, Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now. And it creates the cookie "username" along with the value "StudyGlance" and the default expiry time 0. i,e the cookie will expire as soon as after closing the browser window.
A simple example to understand working with cookies along with expiry time in PHP.
<?php
// To create cookie
setcookie("username", "StudyGlance",time()+1*60*60);
?>
<html>
<body>
<?php
if(!isset($_COOKIE["username"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["username"];
}
?>
</body>
</html>
In the above example program, Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now. And it creates the cookie "username" along with the value "StudyGlance" and with the expiry time 1 hour (1*60*60 seconds or 3600 seconds.) i,e the cookie will expire after 1 hour.