PHP 删除COOKIE

手册中的方法:

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure]]]]] )

<?php
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);
?>

删除一个cookie的方法就是把这个cookie的有效期设置为当前时间以前。


setcookie("testcookie", '');
print_r($_COOKIE);
结果果然是整个$_COOKIE数组都是空的,而非仅仅$_COOKIE['cookie']为
空.

以下转自网络。

以下代码可以在php5.20的 linux 源码包中ext/standard/head.c第99行附近找到.

if (value && value_len == 0) {
/* 
    * MSIE doesn't delete a cookie when you set it to a null value
    * so in order to force cookies to be deleted, even on MSIE, we
    * pick an expiry date 1 year and 1 second in the past
    */
time_t t = time(NULL) - 31536001;
dt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, t, 0 TSRMLS_CC);
sprintf(cookie, "Set-Cookie: %s=deleted; expires=%s", name, dt);
efree(dt);
} else {
sprintf(cookie, "Set-Cookie: %s=%s", name, value ? encoded_value : "");
if (expires > 0) {
strcat(cookie, "; expires=");
dt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, expires, 0 TSRMLS_CC);
strcat(cookie, dt);
efree(dt);
}
}

源码中清清楚楚的显示,if (value && value_len == 0) ,当value_len为0

sprintf(cookie, "Set-Cookie: %s=deleted; expires=%s", name, dt);
会发送删除cookie的http头给浏览器.

最后我们可以得出结论,在php中使用
setcookie($cookiename, '');或者 setcookie($cookiename, NULL);
都会删除cookie,当然这些手册中并没有

你可能感兴趣的:(PHP 删除COOKIE)