All headers must be sent before any text output is sent. Additionally, the cookie will not be available until the page is loaded again: the cookies are sent as part of the request, then the headers are sent from the server, then the text.
In order to avoid the fact that cookies aren't set immediately, I use the following:
PHP Code:
<?php
function setcookielive($name, $value='', $expire=0, $path='', $domain='', $secure=false, $httponly=false) {
//set a cookie as usual, but ALSO add it to $_COOKIE so the current page load has access
$_COOKIE[$name] = $value;
return setcookie($name,$value,$expire,$path,$domain,$secure,$httponly);
}
?>
Note that this stores the value immediately so you can use it but does not verify that the cookie was accepted by the user. Take this into account while designing your system.
If the cookie is not needed until the next page load, there's no real need to use this, but for my purposes I wanted to use the value to change a system setting that would be immediately changed, so I found no reason to wait until later to get the value back.
Bookmarks