note 70522 added to function.setcookie

From: Date: Thu, 19 Oct 2006 15:05:44 +0000
Subject: note 70522 added to function.setcookie
Groups: php.notes 
Request: Send a blank email to php-notes+get-118771@lists.php.net to get a copy of this message
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 } } ?> ---- Server IP: 216.194.113.175 Probable Submitter: 72.152.173.81 ---- Manual Page -- http://www.php.net/manual/en/function.setcookie.php Edit -- https://master.php.net/note/edit/70522 Del: integrated -- https://master.php.net/note/delete/70522/integrated Del: useless -- https://master.php.net/note/delete/70522/useless Del: bad code -- https://master.php.net/note/delete/70522/bad+code Del: spam -- https://master.php.net/note/delete/70522/spam Del: non-english -- https://master.php.net/note/delete/70522/non-english Del: in docs -- https://master.php.net/note/delete/70522/in+docs Del: other reasons-- https://master.php.net/note/delete/70522 Reject -- https://master.php.net/note/reject/70522 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#118771) next »