这是一个来自大型应用程序的示例脚本,但是它展示了我正在尝试完成的一般过程。如果我有以下脚本:
<?php
ob_start();
setcookie('test1', 'first');
setcookie('test1', 'second');
setcookie('test1', 'third');
setcookie('test2', 'keep');
//TODO remove duplicate test1 from headers
ob_end_clean();
die('end test');
我收到了以下的响应(通过 Fiddler 查看):
HTTP/1.1 200 OK
Date: Tue, 25 Apr 2017 21:54:45 GMT
Server: Apache/2.4.17 (Win32) OpenSSL/1.0.2d PHP/5.5.30
X-Powered-By: PHP/5.5.30
Set-Cookie: test1=first
Set-Cookie: test1=second
Set-Cookie: test1=third
Set-Cookie: test2=keep
Content-Length: 8
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
end test
问题在于
Set-Cookie: test1
存在3次,因此不必要地增加了标头大小。 (再次说明,这是一个简化的示例 - 实际上,我正在处理约10个重复的cookie,范围为~800字节。)
有什么可以替代TODO
的内容,可以完全删除标头或仅显示一次吗? 即我的最终目标如下:HTTP/1.1 200 OK
Date: Tue, 25 Apr 2017 21:54:45 GMT
Server: Apache/2.4.17 (Win32) OpenSSL/1.0.2d PHP/5.5.30
X-Powered-By: PHP/5.5.30
Set-Cookie: test1=third
Set-Cookie: test2=keep
Content-Length: 8
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
end test
尽管
Set-Cookie: test1=third
可能不存在,这也没关系,但需要保留Set-Cookie: test2=keep
。当我尝试使用setcookie('test1', '', 1);
删除cookie时,它会添加一个额外的标头来将其标记为过期:Set-Cookie: test1=first
Set-Cookie: test1=second
Set-Cookie: test1=third
Set-Cookie: test2=keep
Set-Cookie: test1=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0
如果我试着去掉头部:
if (!headers_sent()) {
foreach (headers_list() as $header) {
if (stripos($header, 'Set-Cookie: test1') !== false) {
header_remove('Set-Cookie');
}
}
}
它移除了所有的
Set-Cookie
头信息,而我只需要移除test1
。
Set-Cookie: test1=...
已经运行了多次,所以我可以注入任何代码的地方就在TODO
。 - WOUNDEDStevenJones