PHP Cookie
Cookie overview
A cookie is a piece of information stored in user's web browser in text format. A Cookie is stored as one or more name-value pairs which may be encrypted for privacy and security purpose. Cookie also refers as web cookie, HTTP cookie or browser cookie.
Each time users visit a website, web server sends cookies as an HTTP header to the user's web browser. Next time when user visits the website again, the cookies are sent back to the web server so website can read information in it and do the nessesary things such as personalization based on user preferences.
Most modern web browsers allow users to choose whether to accept cookies so you should not rely on cookie 100%. If you use cookie for the website you should inform user that the cookie must be enable in his web browser in order to access the site.
Setting cookie in PHP
PHP make easier by providing setcookie function to allow you to set cookie. Once cookie is set, you can access it through the super global array $_COOKIE.
Here is form of setcookie function.
<?php
setcookie($name, $value, $expire, $path, $domain, $secure);
?>
- $name: Cookie's name. As always it should be meaningful.
- $value: Value of the cookie. It can be scalar value such as string or integer
- $expire: Time to expire in UNIX timestamp. If time to expire is not set cookie will expire when user close the web browser.; for example: time()+"7200". Cookie will be expired in two hours.
- $path: The path on your web server for which the cookie will be returned.
- $domain: domain where cookie will be returned.
- $secure: true to indicate cookie is set over secured HTTP (HTTPS). Default value is false.
Let take a look at an example of setting cookie in PHP.
<?php
setcookie("user","phpcookie",time() + 7200);
?>
<html>
<body>
<p>Cookie has been set to user phpcookie and will be expired in 2 hours.</p>
</body>
</html>
Be noted that cookie must be set before any HTML code as shown above.This is because cookies are headers and must come before the body of the request.
Reading Cookie Value
Once cookie has been set you can get its value via superglobal array $_COOKIE. Before reading cookie value you should check whether the cookie is available by using isset function. Here is the code sample to read cookie value:
<?php
if(isset($_COOKIE['user'])
{
echo 'Welcome '.$_COOKIE['user']. '!';
}
?>
Deleting a cookie
Cookie cannot be deleted but can have different value therefore you can reset cookie value to achieve the same effect as it is deleted by using function setcookie and set the time to expire to the past. Here is the code to delete a cookie:
<?php
if(isset($_COOKIE['user'])
{
setcookie("user", "", time()-3600);
}
?>