What is a Cookie?
A cookie is flat file based system used to represent a user of the website. It is stored on the local computer of the user. When you visit a website a cookie may be set to represent the user. Next time he visits the website, he does not need to identify himself manually; instead the cookie will represent him on that website. With the help of PHP, cookies can be created, read and destroyed.
The main difference between a session and a cookie is that cookies are stored on the user’s computer where as sessions are stored on the server for particular usage. Cookies can be manually deleted by the users also to make sure security is not breached.
Why do we use Cookies?
We can literally put 4000 characters of data in a flat cookie file and store information about the user preferences for a particular website. Some of the practical uses of Cookies are as follows:
- Many sites use them to provide customized pages and results to their users. This can be achieved by storing all the information like preferences etc in a cookie.
. - Many websites use cookies to log their users in automatically. By storing a few pieces of user information they can automatically authenticate the user’s details and use them to save the user time when they log in.
. - Visitor tracking and statistics systems often use them to track visitors. By assigning the visitor a cookie, they will not be counted more than once, so accurate unique visitor statistics can be obtained.
Cookie Security:
Practically there is no security threat while using cookies. A cookie set by a particular website cannot be accessed or even check if it exists by another website even if it wants to. But since cookie is just a flat text file, it can be opened and read on the computer it is stored in.
If a website has stored a password in a cookie it can be read and this can pose threat to hacking. But if the same password is encrypted using a hash like md5() or sha1() then it can be more secure since this content is used to match it with the password stored on the website.
How to Set a Cookie:
In PHP, we have a function setcookie() which is used to SET as well as UNSET the cookie.
Syntax:
setcookie("name", "value", expire, "path", "domain");
Name: it’s the name of the cookie
Value: the value that is to be stored in the cookie. Ex: username, password, email id
Expire: it’s the expiring time of the cookie since it was set.
Path: the path of the website where the cookie is valid. Like a subdomain
Domain: The website this cookie is valid for.
Example
setcookie("username", "Harsha M V", time()+3600);
In the above example, the Cookie name is username. value is Harsha M V, it expires in 1 hour. It is mentioned in seconds 60 seconds multiplied by 60 minutes. The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
How to Retrieve a Cookie Value?
PHP comes with a super global $_COOKIE. All cookies set by a website on their clients website is retrieved via this super global.
<?PHP // Print a cookie
echo $_COOKIE["username"];
// A way to view all cookies as an array
print_r($_COOKIE);
//Using the isset() function we can display messages
//on the screen using the information stored in the cookie.
//Here’s how its done.
if (isset($_COOKIE["username"]))
echo "Welcome " . $_COOKIE["username"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
The above script checks if the cookie with the name username is set. If it is set it prints Welcome “ Harsha M V”. If the cookie is not set then is just prints out Welcome Guest!
How to Delete a Cookie ?
There is no special function to delete a cookie. It can be done by reversing the timing of expiry in the cookie by resetting it again as shown below.
setcookie("username", "", time()-3600);
From the above statement, if you observe the name of the cookie is the same as it was set. The value of the cookie is set to NULL and the expiry time is subtracted from the current time to 1 hour earlier making it to expire at the moment the above function is run.
Practical Example of using a Cookie on a Website:
<?php
if (!isset($_POST['email'])) {
// if form has not been submitted
// display form
// if cookie already exists, pre-fill form field with cookie value
?>
<html>
<head></head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
Enter your email address: <input type="text" name="email" value="<?php echo $_COOKIE['email']; ?>" size="20">
<input type="submit" name="submit">
<?php
// also calculate the time since the last submission
if ($_COOKIE['lastsave']) {
$days = round((time() - $_COOKIE['lastsave']) / 86400);
echo "<br /> $days day(s) since last submission";
}
?>
</form>
</body>
</html>
<?php
}
else {
// if form has been submitted
// set cookies with form value and timestamp
// both cookies expire after 30 days
if (!empty($_POST['email'])) {
setcookie("email", $_POST['email'], mktime()+(86400*30), "/");
setcookie("lastsave", time(), mktime()+(86400*30), "/");
echo "Your email address has been recorded.";
}
else {
echo "ERROR: Please enter your email address!";
}
}
?>
</body>
</html>
Working:
First, when the page is loaded, it checks if the cookie by name Email is set. If not then it displays a form for the user to enter his email ID. Once the USER submits the form it checks if the Email field was filled. If it was filled then a cookie with the name Email is SET with its value set to the user input email ID setting a expiry date along.
Another cookie with the name lastsave is also set with the value set to the current time it was set at. If the email is not entered then it shows a message. Now we can retrieve the cookie using the $_COOKIE super global.
COOKIE mixed with SESSIONS can do wonders for your website. In the next tutorial, let us learn about SESSIONS and how to work with SESSION variables.