Wednesday, March 18, 2009

Working with cookie in php(set, retrieve, delete)

Cookies are the mechanism for storing data in the browser machine and thus tracking the user. With php you can set, retrieve and delete cookies.

Set Cookie:

With the setcookie() function you can send cookie to the browser. The syntax of this function is,
bool setcookie(name, value, expire, path, domain, secure, httponly);

where name is the name that you name the cookie.

value is the information that to be stored in the browser's computer.

expire defines the time the cookie expires.
path term is related to server which indicates the domain that the cookie will be available for. If you set to '/', the cookie will be available within the entire domain. The default value is the current directory that the cookie is being set in.

domain sets whether cookie will be available to subdomain. If you set ".test.com" /"test.com" then in all subdomains of test.com cookie will be available. If you set "mail.mytest.test.com" then the cookie will be available under mail.mytest.test.com subdomain.

secure - which is set to FALSE by default. If it is set then cookie will be only transmitted if it get HTTPS secure connection.

httponly
- If it is set to true cookie will only be accessible for http connection. For scripting language cookie will not be available.

setcookie() function must be placed on the script prior to any output. So it means before <html> tags as well as any whitespaces.

Following is a declaration of a cookie which specifies cookie name will be myCookie, value to be assigned is "Abdul Momin Arju" and after 1 hours cookie should be expired.

<?php
setcookie("myCookie", "Abdul Momin Arju", time()+3600);
?>


The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received. In order to prevent URLencoding, use setrawcookie() function.

Retrieve a Cookie value
Cookie can be accessed by variables $_COOKIE or $_REQUEST or $HTTP_COOKIE_VARS arrays.

Delete a cookie:

When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser.
Example:
<?php
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
?>


The following is an example of set cookie value and displaying on cookie info in the browser.
<?php
$value = 'My Cookie Value';
setcookie("myCookie", $value, time()+3600);
?>


<?php
// Print individual cookie
echo $_COOKIE["myCookie"];
echo $HTTP_COOKIE_VARS["myCookie"];
//print_r($_COOKIE); --For debugging
?>

Related Documents
Working with cookie in php(set, retrieve, delete)
Accessing data from html forms in php
Track error messages on php
Array declaration, assignment and printing in php
Variables in PHP
Constants in php
Magic constants in php

No comments:

Post a Comment