Mmmm…Cookies
Time for a tutorial on PHP Cookies now. Every time you log into a site chances are you’re kept logged in with the help of cookies. Here I will show you a quick guide to cookies.
Syntax and rules.
Cookies must be set before any information is displayed on the page. So set your cookies before the tag and before you echo() or print() anything.
Ok let’s do this…
setcookie(”name”, “Matthew Lodge”, $expire);
The first part of the code sets an expiry date for the cookie. Here it is set for a week from when the cookie is set. (60 seconds, 60 minutes, 24 hours and 6 days). This cookie is called name and will have a value of Matthew Lodge.
This code is fine for setting a cookie but it will reset the cookie every time the page is refreshed. so to keep the current cookie we can use an if statement.
$expire=time()+60*60*24*6;
setcookie(”name”, “Matthew Lodge”, $expire);
}
This if statement checks whether the cookie exists and if it doesn’t it sets it.
Showing the value of a cookie is easy as shown below
//This will show the cookie that is called name
print_r “$_COOKIE”;
//This will print all the cookies in an array
To delete cookies you must set them in the past.
//Sets the cookie an hour in the past and destroys it.
So that’s cookies. Remember that some people do not have cookies enabled so always have a contingency plan if you want your application to be used by all.