Search code examples
wordpresscookiessetcookie

setcookie works but doesn't save in $_COOKIE


I'm trying to set a simple cookie at the beginning (according to the PHP manual):

function set_cookie() {
    if( !isset($_COOKIE['mycookie']) ){

        $value = hash( 'md5', time () . '21mondo13' );
        if ( setcookie( 'mycookie', $value, time() + 60*60*24*7 ) ) {
            $_COOKIE['mycookie'] = $value;
            echo 'cookie set';
        } else {
            echo'cookie NOT set';
        }//if
    }//if

}//set_cookie
add_action( 'init', 'set_cookie' );

but the output is always 'cookie set' even reloading the page or going on a different page. I checked the browsercookies and Ican't find "mycookie"cookie.

Any ideas?

Thanks!


Solution

  • Use this format:

    setcookie('mycookie', $value, time() + 60*60*24*7, '/', null, 0);