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