Cookies in Php

What is a Cookie?

A cookie is often used to identify a user. A cookie is a small file that is stored on the user's computer. Each requests on to page in browser, it also send the cookie too.
We can create and retrieve the cookies in php.

Creating Cookie in Php

In Php setcookie() function is used to set a cookie.
The setcookie() function must appear BEFORE the <html> tag.

Syntax :

setcookie(name, value, expire, path, domain, secure, httponly);

name - The name of the cookie. 
value - The value of the cookie. 
expire - The time the cookie expires
path - The path on the server in which the cookie will be available on
domain - The domain that the cookie is available to. Setting the domain  
to 'www.test.com' will make the cookie available in the www subdomain and higher subdomains.
secure - When TRUE the cookie will be made accessible only through 
the HTTP protocol. This means that the cookie won't be accessible by scripting 
languages, such as JavaScript.
httponly - When set to TRUE, the cookie will only be set if a secure connection 
exists.
Note to Remeber : The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received.
To prevent URLencoding in Cookie we can use setrawcookie().

Example 1

In the example below, we will create a cookie "username" and assign the value "Hiren Prajapati" to it. We also specify that the cookie should expire after one hour:
<?php

setcookie("username", "Hiren Prajapati", time()+3600);

?>
<html>

.....

Example 2

In the example below, we will create a cookie "username" and assign the value "Hiren Prajapati" to it. We also specify that the cookie should expire after one month:
<?php

$expiretime=time()+60*60*24*30;
setcookie("username", "Hiren Prajapati", $expiretime);

?>
<html>

.....

Retrieve a Cookie

We can retrieve a cookie using $_COOKIE variable.

In the example below, we retrieve the value of the cookie named "username" and display it on a page:
<?php

// Print a cookie
echo $_COOKIE["username"];

// print all cookies
print_r($_COOKIE);

?>

We can check the cookie using isset as the example below.

<html>
<body>

<?php

if (isset($_COOKIE["username"]))
  echo "Welcome " . $_COOKIE["username"] . "!<br />";
else
  echo "Welcome Guest!<br />";

?>

</body>
</html>

No comments: