Using Cookies in PHP
By Peter McNulty : 06-02-2005
Cookies as very picky about how they are deleted and usually require that they be removed, using the same values as they were set with. Hence, if we have a domain or path specified, then we must specify this domain/path when deleting the cookie.
To delete a cookie, you simply set the value of the cookie to null, and also set the expiring time of the cookie in the past. Ideally, one would set the expiry time to about a year in the past, so that if the system time is off by a few minutes or days even, then the cookie will still delete correctly.
Let's dive right in:
The above script would delete a cookie called username that was in the domain and path that the script is run in. Notice how to expiry time has been set to a year in the past. This will ensure correct deletion of the cookie.
Going back to our user logon system, we can now create a very simple logout script. This will mean, that the user will have to re-login on the next access attempt to index.php, even if the Remember Me option was set.
See how simple that was? All we had to do, is use the setcookie() function in the same way as before, except setting the value to being empty and the expiry in the past. It is important to set the path and domain otherwise there is a large chance that the cookie will not be deleted.
After our cookies are deleted, the script will redirect back to the login form so that the user can login again. Previously I had mentioned that IIS will not set cookies properly if the header() function is used to redirect. Here is how we could get around this problem:
All that we have done is use the meta refresh HTML tag to do the redirect. Using this method, IIS will work perfectly. So, if you are on a IIS server, then I recommend you replace all the previous header() redirects with this HTML code, replacing the page to be redirected to, to the page needed.
This is all there is to cookies for the majority of thinkable uses. They should provide a mechanism in increasing your sites usability and making it easier for you to manage users.
<< Page 3 of 3