Problem with cookie

0

I would like my script to verify the existence of the informed Cookie and if it did not exist insert, and if it was already existing did not insert.

My code is this:

$protocol    = (strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === true) ? 'https' : 'http';
$host        = $_SERVER['HTTP_HOST'];
$uri        = $_SERVER['REQUEST_URI'];
$current_uri = $protocol . '://' . $host . $uri;

$current_uri = $protocol . '://' . $host . $uri;
$current_url = md5($current_uri); // SOLUÇÃO

if(isset($_COOKIE[$current_url])) { 
    echo "O usuário já tem o cokkie.";
} else {
    setcookie($current_url, date("d-m-Y H:i:s"), time()+3600); // 3600 => 1 hour
    echo "Cookie inserido com sucesso";
}

But it has not worked! The cookie is actually inserted. The problem is that it is always renewed and the message that the Cookie already exists is not passed. Could someone help me?

    
asked by anonymous 25.10.2018 / 21:57

1 answer

0

Name your pages

$nome_pagina = "pagina1";

setcookie($nome_pagina, $nome_pagina, time() + 30, "/");

if(!isset($_COOKIE[$nome_pagina])) {
    echo "Cookie inserido com sucesso";
} else {
    echo "O usuário já tem o cokkie.";
}

If you do not want to put names on pages, use pathinfo - Returns information about a file path

$path_parts = pathinfo( __FILE__ );
$nome_pagina = $path_parts['filename'];

setcookie($nome_pagina, $nome_pagina, time() + 30, "/");

if(!isset($_COOKIE[$nome_pagina])) {
    echo "Cookie inserido com sucesso";
} else {
    echo "O usuário já tem o cokkie.";
}
    
26.10.2018 / 01:19