How to access the COOKIE on another page?

Asked

Viewed 1,814 times

2

I have a file where he creates a cookie. And I have another file where I call this cookie, only it gives me that mistake: Undefined index: name in

Here’s the code from the first file:

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

Here the second one:

echo $_COOKIE['nome'];

As suggested in comment:

print_r($_COOKIE);
[PHPSESSID] => 7t392fumpc1apivqmets57ig90
  • 1

    gives a print_r($_COOKIE); to see what returns and puts here

  • [PHPSESSID] => 7t392fumpc1apivqmets57ig90

  • 2

    It is probably a cookie scope problem. Try to put setcookie("nome", $dataNome, time() + (2 * 3600), "/");. Check the scope of the cookie in your browser’s developer tools.

2 answers

3

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

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

Remembering also to use the ob_end_flush() at the end of the page.

3


PHP Explica

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


You have successfully created the cookie:

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

But to recover, only in the next update as it will not be available before that

echo $_COOKIE['nome'];


For this reason triggers the error Undefined index.


One solution is to create a type of storage for cookies.
When you create a cookie, it will be stored in the class and created by the function setcookie, and when you request the read, it will check if it is in $_COOKIE or if it is in $Storage.


Example of use:

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 ) );
    }
}
  • 1

    Observing: $HTTP_COOKIE_VARS is deprecated and should no longer be used.

  • I gave copy-paste just, thanks I’ll edit

Browser other questions tagged

You are not signed in. Login or sign up in order to post.