| NAME: |
|
Cookies |
| AUTHOR: |
|
punkstar |
| DATE: |
|
24th Nov, 2005 - 04:57:55 AM |
| DESCRIPTION: |
|
A guide to using cookies in PHP |
Need some help with that coding?
What are cookies?
Cookies are little packets of information that are stored locally on a computer system when you visit a website that utilizes them.
How can they be used?
Cookies can be used to store indentifiable information about a user on their computer so that the website can then pick up on it later, evern after your computer has been turned off, and you may continue from where you started.
An example of this is with member systems and forums, when you are offered the "Remember me" option. With that, the website stores your username on your computer, and it can then find it when you log on to the website next, and enter your username automagically in the textbox.
How do i use them?
Cookies are pretty easy to use, but you must remember that some people may not like the idea of having little pieces of information at all stored on their computer, as this can lead to people finding out what kind of sites you have been on etc (not that your site is bad, right?)
| PHP Code |
<?php
setCookie("CookieName", "CookieValue");
if(isset($_COOKIE['CookieName']))
{
echo "CookieName = $_COOKIE['CookieValue']";
}
else
{
echo "Cookie Set, please refresh the page!";
}
?>
|
..now what if you want a certain cookie to run out after a certain length of time? This is simple. First we need to work out the timestamp for the time that we want it to run out at.
| PHP Code |
<?php
$runoutat = time() + (60 * 60); //in one hour
$runoutat = time() + (60 * 60 * 2); //in two hour
$runoutat = time() + (60 * 60 * 24); //in one day
$runoutat = time() + (60 * 60 * 24 * 7); //in one week
?>
|
Simple maths =D, all you are doing is adding seconds to the current timestamp. Now to add it to the cookie call.
| PHP Code |
<?php
$runoutat = time() + (60 * 60 * 24 * 4);
setCookie("CookieName", "CookieValue",$runoutat); //expire in 4 days
?>
|
..and its equally as easy to unset cookies, all you need to do it set the cookie expiry date to a time that has already passed. Its good practise to unset with the dame amount of time that you set it to, then you can make sure that it has unset itself =D.
| PHP Code |
<?php
$runoutat = time() - (60 * 60 * 24 * 4);//<-- notice the negative
setCookie("CookieName", "CookieValue",$runoutat); //expire the cookie now
?>
|
So to unset, we reset the cookie with an expiry time that is less than the current time, this will then eliminate the cookie. We are setting the expiray date to four days ago above.
Easy. Cookies can be a huge help in providing dynamic php content! Enjoy!
|