Skip to content

Working with Cookie

April 22, 2013
1.     What is a Cookie?
Cookie is used to identify a user. It is a small file which is automatically get embedded by server on the user’s computer or PC. Every time when the computer requests a page using browser it sends the cookie too. Using PHP we can create or retrieve cookie values.

2.      How to Create a Cookie?
In PHP the setcookie() function is used to create cookie.
Note: setcookie() must appear before the <html> tag.
Syntax:-

setcookie(cookiename, value, expiringtime, path, domainname);

Example:
Given example will create a cookie named “PHPCookie” and will assign the value “PHPUser”. We’ll also specify the cookie should expire after one hour too:

<?php
setcookie(“PHPCookie”, “PHPUser”, time()+3600);
?>
<html>
……
        ……
Note: Value of the cookie will automatically URLencoded when sending the cookie and automatically decoded when received.

3.      How to Retrieve a Cookie Value?
To retrieve the cookie value PHP provides $_COOKIE variable in built.
Given below example will retrieve the value of cookie named “PHPCookie” and display it on a page:
<?php
// Print a cookie
echo $_COOKIE[“PHPCookie”];
// To view all cookies
print_r($_COOKIE);
?>
In this example we’ll use the isset() function to find out if a cookie has been set or not:
<html>
<body>
<?php
if (isset($_COOKIE[“PHPCookie”]))
echo “Welcome ” . $_COOKIE[“PHPCookie”] . “!<br>”;
else
echo “Welcome guest!<br>”;
?>
</body>
</html>

4.     How to Delete a Cookie?
To delete a cookie we should assure that the expiration date is in the past. Otherwise it’ll through the error.
Example to Delete Cookie:
<?php
// set the expiration date to one hour ago
setcookie(“PHPCookie”, “”, time()-3600);
?>

Leave a Comment

Leave a comment