php 删除cookie有效方法,php删除cookie_PHP教程

WBOY
Release: 2016-07-13 10:12:54
Original
891 people have browsed it

php 删除cookie有效方法,php删除cookie

php 删除cookie有效方法
关于删除cookie的说明开始-----

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

要删除cookie需要确保它的失效期是在过去,才能触发浏览器的删除机制。

下面的例子说明了如何删除刚才设置的cookie:
//将过期时间设为一小时前
setcookie("TestCookie", "", time() - 3600);
setcookie("TestCookie", "", time() - 3600, "/~rasmus/", ".utoronto.ca", 1);
?>


-----关于删除cookie的说明结束-----

删除一个cookie的方法就是把这个cookie的有效期设置为当前时间以前,这也是几乎所有php程序员都会这么做。

后来一个初接触php的朋友告诉我,他在程序中本想把一个cookie的值设置为空,结果导致这个cookie直接被删除。我当时的第一反应是不相信,于是测试
了一下:
setcookie("testcookie", '');
print_r($_COOKIE);


结果果然是整个$_COOKIE数组都是空的,而非仅仅$_COOKIE['testcookie']为空。于是用winsock抓包,观察返回的http头,发现http头竟然是“Set-Cookie: testcookie=deleted; expires=Mon, 18-Jun-2007 02:42:33 GMT”,这说明“setcookie("testcookie", '');”的的确确是将testcookie这个cookie直接删除,而关于这种情况在php手册中完全没有说明。

最后阅读php源码,终于发现真相(这就是开源的好处了,有什么不清楚的内幕,直接查源码)。

以下代码可以在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,当然这些手册中并没有。

来源:http://www.111cn.net/phper/21/f0eace11b1229a0f2c7c54e3c1ea4654.htm

www.bkjia.com true http://www.bkjia.com/PHPjc/918673.html TechArticle php 删除cookie有效方法,php删除cookie php 删除cookie有效方法 关于删除cookie的说明开始----- bool setcookie ( string name [, string value [, int expire [, str...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!