Pages

Friday, October 29, 2010

Cookies

Cookies are simple little text files used to store pieces of data on a site visitor's computer, allowing the site to keep track of what a visitor is doing during their visit, or across multiple visits. They are most commonly used for personalising a site to the visitor, such as remembering which skin the visitor prefers or storing user information so they don't need to log in every time they visit. Creating, reading and deleting cookies is very simple to do with PHP.
Creating Cookies
Creating a cookie is easy peasy, but before you start, there is an important rule to follow: The cookie code must be the first line of your file, before the head of your page, any other code or even a blank line. If not, you will get aHeaders already sent error. So to set a cookie, your page should look like this:
<?php
setcookie ("cookie", "This text will be in the cookie");
?>
<html>
<head>
<title>Page Title</title>
</head>
<body>
etc.
This stores a variable on the user's computer with the name "cookie" which contains the value "This text will be in the cookie". If you would like to store multiple variables, just set more cookies!
<?php
setcookie ("cookie", "This text will be in the cookie");
setcookie ("cookie2", "This text will be in the next cookie");
setcookie ("cookie3", "You can set anywhere up to twenty cookies per user");
?>
Reading Cookies
Once the cookie is set, it can be read from the next page. Using the echo() function with the cookie name will display the contents of that cookie. Like so:
<?php
echo $_COOKIE["cookie"]; // Will display "This text will be in the cookie"
echo $_COOKIE["cookie2"];  // Will display "This text will be in the next cookie"
echo $_COOKIE["cookie3"];  // Will display "You can set anywhere up to twenty cookies per user"
?>
Remember that everything after // is a comment to yourself.
Deleting Cookies
When cookies are created, they are set by default to be deleted when the user closes their browser. If you wish instead to set a time limit for the cookie, you can set an expiration time with it:
<?php
setcookie ("cookie", "This text will be in the cookie", time( ) + 3600);
?>
Adding the time() paramater plus (+) the number of seconds will set the time from now that the cookie will expire. In the example above the cookie will expire in one hour.
If, however, you wish to delete the cookie before the user closes their browser, and before its expiration time, such as with a "log out" option, just use the setcookie() function for the same cookie, but with a negative number for the time parameter. Like so:
<?php
setcookie ("cookie", "", time( ) - 1);
?>

0 Comments:

Post a Comment