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 ) );
}
}
gives a print_r($_COOKIE); to see what returns and puts here
– Otto
[PHPSESSID] => 7t392fumpc1apivqmets57ig90
– Meeeefiu
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.– Vinícius Gobbo A. de Oliveira