Element
04-25-2008, 09:15 PM
Having trouble setting cookies? Try setting the globally, or alternately again, by headers.
Had to use this on a clunky host. I hope people don't have this problem, but if you do, here is a fix. Note, if it fails to set the cookie globally, it will try by headers, which is not possible unless the function is called before any output.
<?php
function setaltcookie( $name, $value, $expires ) {
// Use up to two digits to define a expiration in days.
$expires = ( ( strlen( $expires ) <= 2 ) ? ( time() + ( 86400 * $expires ) ) : ( time() + $expires ) );
$global = @setcookie( $name, $value, $expires, '/', '/' );
if ( ! ( $global ) ) {
// If we can't set the cookie globally, try setting a cookie by headers.
$header = @header('Set-Cookie: ' . $name . '=' . $value . '; expires=' . $expires . '; path=/; domain=' . $_SERVER['HTTP_HOST'] );
return $header;
}
return $global;
}
if ( setaltcookie( 'demo-cookie', md5( microtime( true ) ), 7 ) ) {
echo 'The cookie should now be set.';
} else {
echo 'Hmm, nope.';
}
?>
Had to use this on a clunky host. I hope people don't have this problem, but if you do, here is a fix. Note, if it fails to set the cookie globally, it will try by headers, which is not possible unless the function is called before any output.
<?php
function setaltcookie( $name, $value, $expires ) {
// Use up to two digits to define a expiration in days.
$expires = ( ( strlen( $expires ) <= 2 ) ? ( time() + ( 86400 * $expires ) ) : ( time() + $expires ) );
$global = @setcookie( $name, $value, $expires, '/', '/' );
if ( ! ( $global ) ) {
// If we can't set the cookie globally, try setting a cookie by headers.
$header = @header('Set-Cookie: ' . $name . '=' . $value . '; expires=' . $expires . '; path=/; domain=' . $_SERVER['HTTP_HOST'] );
return $header;
}
return $global;
}
if ( setaltcookie( 'demo-cookie', md5( microtime( true ) ), 7 ) ) {
echo 'The cookie should now be set.';
} else {
echo 'Hmm, nope.';
}
?>