How to access COOKIE on another page?

3

I have a file in which it creates a cookie. And I have another file in which I call this cookie, but it gives me this error: Undefined index: name in

Here is the code for the first file:

setcookie('nome', $dataNome', time() + (2 * 3600));

Here the second:

echo $_COOKIE['nome'];

As suggested in comment:

print_r($_COOKIE);
[PHPSESSID] => 7t392fumpc1apivqmets57ig90
    
asked by anonymous 28.08.2014 / 22:02

2 answers

3

PHP Explains

  

Once the cookie has been set, it can be accessed on the next page through the $ _COOKIE

You have successfully created the cookie:

setcookie( 'nome' , $dataNome , time() + (2 * 3600) );

But to recover, only in the next update, since it will not be available sooner

echo $_COOKIE['nome'];


For this reason it triggers the error Undefined index .

One solution is to create a storage type for cookies. When you create a cookie, it will be saved in the class and created by the setcookie function, and when you request it, it will check if it is in $ _COOKIE or if it is in $ storage. Home | Example Usage:

Cookie::writer( 'nome' , 'Papa Charlie' );
Cookie::reader( 'nome' );


Cookie / storage class

class Cookie
{
    private static $storage = array();

    public static reader( $key )
    {
        if( isset( $_COOKIE[ $key ] ) )
        {
            return $_COOKIE[ $key ];
        }
        else
        {
            if( isset( static::$storage[$key] ) )
            return static::$storage[$key];
        }
    }

    public static writer( $key, $value /* outros parametros de criação de cookie */ )
    {
        static::$storage[$key] = $value;
        setcookie( $key , $value , time() + ( 2 * 3600 ) );
    }
}
    
28.08.2014 / 22:56
3

Make sure you are not sending any output to the browser before the setcookie() function.

ob_start () must stop the output before the error " setcookie () ", but can not be implemented correctly.

Also remember to use ob_end_flush() at the bottom of the page.

    
28.08.2014 / 22:11