A cookie is used to identify a user. A cookie is a small file that is embedded by the server on the user’s computer. In this when the same computer requests for a page with a browser, it will send the cookie too. Each cookie consists of a name, value, expiry date, and host and path information. The size of an individual cookie is limited to 4 KB. With PHP, cookie values can be created and retrieved.
Creating Cookie
The setcookie() function is used to create cookies. The setcookie() function should be called before any other content is sent to the browser. The setcookie() function appears before the HTML tag.The setcookie() function accepts the cookie name, cookie value, expiry date, path, and domain. All the arguments to this function are optional apart from the cookie name parameter.
Setcookie(name, value, expire, path, domain);
Example
<?php
setcookie("usal", $sal, time()+3600);
?>
<html>
<body>
<p>
A cookie was set on this page! The cookie will be active when the client has sent the cookie back to the server.
</p>
</body>
</html>
In the above a example a cookie named usal was set with the setcookie() function. This cookie will expire in one hour as the parameter of time given in the function is set to 1 hour.
Retrieving a Cookie Value
When a cookie is set, then the cookie name is used as a variable by PHP. To access the cookie the cookie name has to be referred as a variable.Example
<html>
<body>
<?php
if (isset($_COOKIE["usal"]))
echo "Welcome " . $_COOKIE["usal"] . "!<br / >";
else
echo "You are not logged in!<br /> ";
?>
</body>
</html>
0 comments:
Post a Comment