bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure]]]]] )
要删除 cookie 需要确保它的失效期是在过去,才能触发浏览器的删除机制。下面的例子说明了如何删除刚才设置的 cookie: 例子 2. setcookie() 删除
例子
// 将过期时间设为一小时前
setcookie(testcookie, , time() - 3600);
setcookie(testcookie, , time() - 3600, /~rasmus/, .utoronto.ca, 1);
php删除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删除cookie源码,终于发现真相(这就是开源的好处了,有什么不清楚的内幕直接查源码)
以下php删除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);
会发送php删除cookie的http头给浏览器.最后我们可以得出结论,在php中使用
setcookie($cookiename, '');或者 setcookie($cookiename, null);
都会实现php删除cookie,当然这些手册中并没有。
http://www.bkjia.com/phpjc/445947.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/445947.htmltecharticle首先我们看一下php手册中关于php删除cookie的说明 bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure]]]]] ) 要删...
