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.
setcookie(name, value, expire, path, domain);
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…
$expire=time()+60*60*24*6;
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.
if(!isset($_COOKIE["name"])){
$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
echo $_COOKIE["name"];
//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.
setcookie(”name”, ” “, time()-3600;
//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.