PHP Cookies
Cookies are little packets of information that
are stored locally on a computer system when you visit a website that utilizes
them. Cookies are part of HTTP header, so cookies must be set before
sending any value to the browser (i.e. before html tag).
Cookies can be used to store identifiable information about a user on their
computer so that the website can pick up it later, even after your computer has
been turned off, and you may continue from where you started.
Syntax of cookie is :
setcookie(name, value, expire, path, domain)
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.
Cookies are pretty easy to use, but you must remember that some people may not like the idea of having little pieces of information get stored on their computer, as the consequences other people might come to know about the secret data.
Example 1:
<?php
setCookie("Name","roseindia");
if(isset($_COOKIE['Name']))
{
echo $_COOKIE['Name'];
}
else
{
echo "Cookie set, please refresh the page";
}
?>
Output:
roseindia
Example 2:
<?php
setCookie("Name","roseindia");
SETCOOKIE("ADDRESS","NEW DELHI");
SETCOOKIE("TIME",date("M d y"));
if(isset($_COOKIE['Name']))
{
echo $_COOKIE['Name'];
}
else
{ 0
echo "Cookie set, please refresh the page";
}
print_r($_COOKIE); 1
?>
Output:
roseindiaArray ( [Name] => roseindia [ADDRESS] => NEW DELHI [TIME] => Nov 09 09 )
Example 3 (You can set the time of expiration): 2
If you want to set the time of expiration to 1 hr. then do as follows:
<?php
setCookie("Name","roseindia"); 3
SETCOOKIE("ADDRESS","NEW DELHI");
SETCOOKIE("TIME",date("M d y"),time()+60);
if(isset($_COOKIE['Name'])) 4
{
echo $_COOKIE['Name'];
} 5
else
{
echo "Cookie set, please refresh the page"; 6
}
print_r($_COOKIE);
?> 7
Output:
roseindiaArray ( [Name] => roseindia [ADDRESS] => NEW DELHI [TIME] => Nov 09 09 )
Certainly the output is not different from the previous one, but the values will not exist in the cookie more than one hour.
Example 4 (How to delete a cookie): 8
<?php
SETCOOKIE("user","",time()-3600);
if(isset($_COOKIE['Name'])) 9
{
echo $_COOKIE['Name'];
} 0
else
{
echo "Cookie set, please refresh the page"; 1
}
print_r($_COOKIE);
?> 2
Time should be set to previous time to clear the cookie.