Cookies can be very useful when you need to let the user browser remember stuff, for example how many times a user has visited your web site.
Cookies are sat with the command
setcookie(). Two variables are required and can't be ignored. They are
cookiename and
cookieinformation:
Code:
<?
setcookie("cookiename","cookieinformation");
?>
The above example will set a cookie called cookiename with the information cookieinformation stored in it. The cookie will expire when the browser is closed and can be accessed like this:
Code:
<?
echo $_COOKIE['cookiename'];
?>
This will print cookieinformation on the screen.
Before we can do some programming examples, we need to understand how cookies work. Cookies must be set before any other headers sent to the browser. This means that you can't have any HTML code before setcookie();.
When a cookie is sat it can't be accessed like a cookie on the same page setting the cookie. This means that you can't access the cookie information unless the page is reloaded first (or the user visits another web page).
Cookies can only be accessed from the same domain setting the cookie in the first place. You can't set a cookie at
http://www.sampleaddress.com and then think you can use the cookie information on someothersubdomain.sampleaddress.com. You can of course get around this by setting the cookie like this:
Code:
<?
setcookie("cookiename","cookievariable", time()+31536000,"/", ".sampleaddress.com");
?>
As you can see in the example above I have used a dot infront of the domain name and I ingored www. This way the cookie can be accessed on all subdomains at sampleaddress.com, i e on both
http://www.sampleaddress.com and someothersubdomain.sampleaddress.com.