note 70522 deleted from function.setcookie by bjori
| From: | bjori@php.net | Date: | Mon, 08 Jan 2007 10:53:55 +0000 |
| Subject: | note 70522 deleted from function.setcookie by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-121442@lists.php.net to get a copy of this message | ||
Note Submitter: jlevene at gmail dot com
----
It's just too "dangerous" to use setcookie() directly, since so many things have to
be just right if you ever want to be able to delete the cookie (or even use it again, sometimes).
Here's a very simple little function to painlessly set and delete a cookie. I tried to
incorporate all the "tricks" the people below mentioned, like stripping the
"www." and any port number from the domain, and making the cookie available to any script
on the server.
This function is ready for use by any newbie. Don't be afraid; it's really as easy as it
looks! Just use a value of "" when you want to delete the cookie. The only things you
have to know to use this are:
1) You need to (un)set any cookies you set BEFORE you
produce any output, including <html> or a blank line.
2) A "session" cookie is one that expires when the browser
window is closed.
This function and the 2 above points are intended to make it unnecessary for a newbie to wade
through all this doc to "just use cookies." The example is for a 1-day cookie, but it
should be obvious how to use different durations (bear in mind that the expiration is done by the
browser which may be in a different timezone).
(The $host is global so it only has to be calculated once, in case you have several cookies.)
<?php
$cookieExpire = time() + (60*60*24); // 1 day ("= 0" for Session)
...
$host = preg_replace('/^[Ww][Ww][Ww]\./', '',
preg_replace('/:[0-9]*$/', '', $_SERVER[HTTP_HOST]));
function mySetCookie($cName, $cValue)
{
global $cookieExpire, $host;
if (strcmp($cValue, "") == 0)
{
setcookie($cName, "", 1, "/", ".$host", FALSE); // Delete
}
else
{
setcookie($cName, $cValue, $cookieExpire, "/", ".$host", FALSE);
$_COOKIE[$cName] = $cValue; // Pretend it's already set
}
}
?>