note 68350 added to function.setcookie

From: Date: Mon, 24 Jul 2006 11:58:35 +0000
Subject: note 68350 added to function.setcookie
Groups: php.notes 
Request: Send a blank email to php-notes+get-115082@lists.php.net to get a copy of this message
If a user accesses a page by using www.example.com/page.php and this page issues a cookie, and if the user tomorrow accesses the same page by using example.com/page.php, your page will not be able to retrieve the previous cookie because it was set for "www.example.com" and will set a new cookie for "example.com". To avoid this kind of problems, you can use a solution like this: <?php // Get domain without www and any port (if present) $domain = getDomain(); // Set expiration (30 days) $expire = time() + (86400*30); // Set the cookie setcookie('cookieName', 'cookieValue', $expire, '/', $domain); function getDomain() { if ( isset($_SERVER['HTTP_HOST']) ) { // Get domain $dom = $_SERVER['HTTP_HOST']; // Strip www from the domain if (strtolower(substr($dom, 0, 4)) == 'www.') { $dom = substr($dom, 4); } // Check if a port is used, and if it is, strip that info $uses_port = strpos($dom, ':'); if ($uses_port) { $dom = substr($dom, 0, $uses_port); } // Add period to Domain (to work with or without www and on subdomains) $dom = '.' . $dom; } else { $dom = false; } return $dom; } ?> This sets the cookie's domain without the "www" (and any port) and you can access the cookie from any page on the domain and also from subdomains. If someones find any problem with this solution, please post a comment. HTH ---- Server IP: 66.163.161.117 Probable Submitter: 82.155.246.103 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/function.setcookie.php Edit -- http://master.php.net/note/edit/68350 Del: integrated -- http://master.php.net/note/delete/68350/integrated Del: useless -- http://master.php.net/note/delete/68350/useless Del: bad code -- http://master.php.net/note/delete/68350/bad+code Del: spam -- http://master.php.net/note/delete/68350/spam Del: non-english -- http://master.php.net/note/delete/68350/non-english Del: in docs -- http://master.php.net/note/delete/68350/in+docs Del: other reasons-- http://master.php.net/note/delete/68350 Reject -- http://master.php.net/note/reject/68350 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#115082) next »