Recipe 8.3. Deleting Cookies


8.3.1. Problem

You want to delete a cookie so a browser doesn't send it back to the server. For example, you're using cookies to track whether a user is logged in to your web site, and a user logs out.

8.3.2. Solution

Call setcookie( ) with no value for the cookie and an expiration time in the past, as in Example 8-7.

Deleting a cookie

<?php setcookie('flavor','',1); ?>

8.3.3. Discussion

It's a good idea to make the expiration time a long time in the past, in case your server and the user's computer have unsynchronized clocks. For example, if your server thinks it's 3:06 P.M. and a user's computer thinks it's 3:02 P.M., a cookie with an expiration time of 3:05 P.M. isn't deleted by that user's computer even though the time is in the past for the server.

The call to setcookie( ) that deletes a cookie has to have the same arguments (except for value and time) that the call to setcookie( ) that set the cookie did, so include the path, domain, and secure flag if necessary.

8.3.4. See Also

Recipe 8.1 shows how to set cookies; Recipe 8.2 shows how to read cookie values; Recipe 8.12 explains output buffering; documentation on setcookie( ) at http://www.php.net/setcookie.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net