PHP - Cookies, how to detect if it is created

0

How do I detect if a cookie exists?

My cookie is created like this:

setcookie("log", "true", time()+60, "/classes");

And to detect I'm trying this:

if (!isset($_COOKIE['log'])) {
   //função
}

But it does not detect the cookie, it runs the function inside the if if the cookie exists.

Follow the cookie data in chrome:

Nome:   log
Conteúdo:   true
Caminho:    /classes
Enviar para:    Qualquer tipo de conexão
Acessível ao script:    Sim
Criado em:  segunda-feira, 12 de setembro de 2016 14:05:10
    
asked by anonymous 12.09.2016 / 19:12

2 answers

1

Well you are doing a validation if DOES NOT EXIST your Cookies, so your function will only be executed if the cookie is not created, remembering that "!" in validation does the inverse of the caught "isset". And see if you really exite the directory / classes in your project where you saved this cookie. I hope I have helped and good luck!

    
13.09.2016 / 07:14
-2

It is not clear where you are invoking isset() . So the answer assumes you are on the same page where you invoked setcookie() .

In this case it will not be accessible unless you explicitly declare in the global variable $_COOKIE .

setcookie("log", "true", time()+60, "/classes");
var_dump($_COOKIE); // Não retorna o índice "log", registrado acima em 'setcookie()'

This happens because the global variable $_COOKIE with the index "log" will only be available on the next request.

To make it available on the same page where it is created, it should be explicitly stated:

setcookie('log', true, time()+60, '/classes');
$_COOKIE['log'] = true;

Note: This behavior varies depending on the browser and its version. Of course, always seven explicitly the global variable.

To make it more practical and reusable, create a routine:

function CookieSet($k, $v) {
    setcookie($k, $v, time()+60, '/classes');
    $_COOKIE[$k] = $v;
}

CookieSet('log', true);

Obviously check that the fourth parameter of setcookie() is correct

You are setting '/classes' . You may want to use '/' .

Setting to '/classes' , you are limiting cookies to the '/classes' directory. ex: http://localhost/classes . If you access http://localhost/ , they will not be available.

    
13.09.2016 / 15:13