[TOC] # 注意事项 我们知道,php的setcookie和header都可以设置cookie。但是使用header的时候,还有个注意事项:那就是header和setcookie之间的先后顺序,甚至header和header之间的先后顺序。 header("Set-Cookie:")会清除掉:本语句调用之前的,所有的header("Set-Cookie:")和setcookie(setrawcookie)的效果。见下面的例子,设置了四个cookie。但是实际上只有一个生效。因为另外三个被最后一个给冲掉了。 ~~~ header("Set-Cookie:cookie_name1_cp=" . urlencode("浏览器关闭失效")); setcookie("cookie_name1", "浏览器关闭失效"); setcookie("cookie_name3", "设置有效域名/https/httponly", time() + 3600*24, "/", $_SERVER['SERVER_NAME'], isset($_SERVER["HTTPS"]),true); header("Set-Cookie:cookie_name3_cp=" . urlencode("设置有效域名/https/httponly") . "; expires=" . gmstrftime("%a, %d-%b-%Y %H:%M:%S GMT", time() + 3600*24) . "; Max-Age=3600; path=/; domain= ".$_SERVER['SERVER_NAME']."; httponly"); ~~~ **解决问题方案一** 都使用setcookie函数来控制,那必是极好的,setcookie函数不会相互冲突。即使重名,只要重要信息不同,也是可以同时存在的。(也就是说,重名的话,存在替换的可能性)。 ~~~ setcookie("cookie_name1", "浏览器关闭失效"); setcookie("cookie_name1", "设置有效域名/https/httponly", time() + 3600*24, "/", $_SERVER['SERVER_NAME'], isset($_SERVER["HTTPS"]),true); ~~~ **解决问题方案二** 为header增加第二个参数,false。就是说: ~~~ header("Set-Cookie:xxxxxxxxxxxxxxxx",false); ~~~ 例如: ~~~ header("Set-Cookie:cookie_name3_cp=" . urlencode("设置有效域名/https/httponly") . "; expires=" . gmstrftime("%a, %d-%b-%Y %H:%M:%S GMT", time() + 3600*24) . "; Max-Age=3600; path=/; domain= ".$_SERVER['SERVER_NAME']."; httponly;"); header("Set-Cookie:cookie_name3_cp2=" . urlencode("设置有效域名/https/httponly") . "; expires=" . gmstrftime("%a, %d-%b-%Y %H:%M:%S GMT", time() + 3600*24) . "; Max-Age=3600; path=/; domain= ".$_SERVER['SERVER_NAME']."; httponly;",FALSE); ~~~ 这样的话,使用了false参数的header就不会冲突掉原有的了。 具体可以参见header的php函数说明: ~~~ void header ( string $string [, bool $replace = true [, int $http_response_code ]] ) ~~~ 我们的false,设置的就是参数$replace,就是不替换已有同类型header的意思。注意是“同类型”。