简体   繁体   中英

Why i can not delete cookie using php?

Why i can not delete cookie using php ?

I use this code

<?PHP
session_start();
include("connect.php");
setcookie("rel", "", time() - (86400 * 90) , "/","", 1);
?>

And this code

<?PHP
session_start();
include("connect.php");
setcookie("rel", "", time()-3600);
?>

But cookie still remain.

How can i do ?

You have to kill it...

In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.

Please have a look to an older question: Best way to completely destroy a session - even if the browser is not closed

You are setting the cookie by using the following function:

setcookie("rel", "", time() - (86400 * 90) , "/", "", 1);

The fourth parameter ( "/" ) describes the path the cookie is set on.

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.

Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string, or FALSE, and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client. This is internally achieved by setting value to 'deleted' and expiration time to one year in past.

php.net

If you want to delete the cookie, you have to delete it with the right path, in your case "/" , you might want to use the following function call to let the cookie expire:

setcookie("rel", "", time() - 3600, "/");

Use this code to clear the cookie you want:

setcookie('rel', '', time() - 3600, '/');

This will do the trick

=> Try this code ..

setcookie("rel", "", time()-3600);

OR

 if (isset($_COOKIE['rel'])) {
    unset($_COOKIE['rel']);
    setcookie('rel', '', time() - 3600, '/'); // empty value and old timestamp
}

There is not a way to directly delete a cookie. Just use setcookie with expiration date in the past, to trigger the removal mechanism in your browser.

$cookie_name = 'rel';
unset($_COOKIE[$cookie_name]);
$res = setcookie($cookie_name, '', time() - 3600);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM