How to delete COOKIES in PHP?

6

How can I delete COOKIES in PHP? I know that for sessions it has session_destroy() but for Cookies how do I do it?

    
asked by anonymous 21.02.2016 / 19:22

4 answers

7

Use the setcookie() function but with negative value in the third parameter (which is the expires ), you can also use unset() with the variable $_COOKIE to delete the key in the current execution:

function unsetcookie($key, $path = '', $domain = '', $secure = false, $httponly = false)
{
    if (isset($_COOKIE[$key])) {
        setcookie($key, null, -1, $path, $path, $domain, $secure, $httponly);
        unset($_COOKIE[$key]);
    }
}

//Elimina o cookie pro path atual
unsetcookie('meucookie');

//Elimina o cookie pro path raiz
unsetcookie('meucookie', '/');

//Elimina o cookie de um domínio quando estiver em um subdomínio por exemplo: bar.foo.com
unsetcookie('meucookie', '/', 'foo.com');

As in the documentation example: link

    
21.02.2016 / 19:39
2

The response from the @GuilhermeNascimento answers the question very well, but I would like to add an extra.

When it comes to Cookies, I do not know if the correct way would be to say "Delete Cookies". What is usually done to make Cookie "Deleted" is "invalidate".

I say this because the most common way is to set a negative value for the $expire parameter. This will make the browser understand that Cookie has already "expired" and will not send it to the server.

In a simplified way, you delete a cookie like this:

 setcookie('quero_apagar_isso', null, -1);

Logically thought, one would think that unset($_COOKIE['quero_apagar_isso']) would work, but this is not true.

The variable $_COOKIE is just as read-only because it references something from the client.

The only case where unset will work with a Super Global variable is in the $_SESSION variable.

Only reflect: If you used unset($_GET['id']) , the id parameter would disappear from the url? . Obviously not. Similarly Cookie will not cease to exist just because you deleted a value that references it in PHP.

In the same way that you could only delete the id parameter of a url through redirection, you will only be able to delete the Cookie by setting it in a way that the Browser considers invalid.

    
14.09.2016 / 13:49
1

Do as follows:

<?php

unset($_COOKIE['nome_cookie']);
setcookie('nome_cookie', null, -1, '/');
    
21.02.2016 / 19:42
-3

Facinho, my dear. The command is unset($_COOKIE['nomeDoCookie']);

Ready will already help you with your problem.

That's good luck!

    
14.09.2016 / 05:01