note 68350 deleted from function.setcookie by bjori
| From: | bjori@php.net | Date: | Mon, 08 Jan 2007 10:52:18 +0000 |
| Subject: | note 68350 deleted from function.setcookie by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-121438@lists.php.net to get a copy of this message | ||
Note Submitter: Charles Martin
----
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