【发布时间】:2017-09-23 03:03:07
【问题描述】:
这是来自大型应用程序的示例脚本,但显示了我正在尝试执行的一般过程。如果我有以下脚本:
<?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 次不同的时间,因此不必要地增加了标头大小。 (同样,这是一个简化的例子——
实际上,我正在处理约 800 字节范围内的约 10 个重复 cookie。)
我可以写什么来代替 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');
}
}
}
当我只想删除 test1 时,它会删除所有 Set-Cookie 标头。
【问题讨论】:
-
你能把标题存储在一个数组中吗?例如如果你有一个 View 类,它可能有一个(静态?)方法 SetCookie() ,它将键和值存储在关联数组中。然后在发送最终标头时,只需遍历该关联数组并调用 setcookie(),每个键只会调用一次...
-
我希望!理想情况下就是这样设置的,但是当它到达我的脚本时,
Set-Cookie: test1=...已经运行了多次,所以我可以注入任何类型代码的地方是TODO
标签: php cookies http-headers setcookie response-headers