PHP Cookies

Cookies allow the webmaster to store information about the site visitor on their computer to be accessed again the next time they visit.

Syntax

The setcookie() function is used to set a cookie.

Note: The setcookie() function must appear BEFORE the <html> tag.

setcookie($name, $value, $expire, $path, $domain, $secure)

* $name – name of the cookie. Example: “username”
* $value – value of the cookie. Example: “qpt”
* $expire – time (in UNIX timestamp) when the cookie will expire. Example: time()+”3600″. Cookie is set to expire after one hour.

* $path – path on the server where cookie will be available.
For example, if the path is set to “/”, the cookie will be available through out the whole site. If the cookie is set to say “/news/”, the cookie will only be available under /news/ and all its sub-directories.
If no path is given, cookie in created under the current directory.

* $domain – domain where cookie will be available. Instead of path you can use domain settings.
For example, if the domian is set to “.yourdomian.com”, the cookie will be available within the domain and all its sub-domains, example news.yourdomain.com.

If the cookie is set say “www.yourdomian.com” the cookie will be available under all www sub-domains, example ” www.yourdomian.com/news”

* $secure – true if cookie is being set over a secure “https” server, false otherwise, Default value is false.

In the example below, we will create a cookie named “username” and assign the value “qpt” to it. We also specify that the cookie should expire after one hour:

<?php
setcookie("username", "qpt", time()+3600);
?>

Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

Retrieve a Cookie Value

The PHP $_COOKIE variable is used to retrieve a cookie value.

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"];

// A way to view all cookies
print_r($_COOKIE);
?>

Delete a Cookie

When deleting a cookie you should assure that the expiration date is in the past.

<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>

Posted in Php