使用PHP& amp;标题顺序卷曲

时间:2013-05-23 00:41:44

标签: php curl

我使用以下PHP代码发送带有特定标头和cookie的GET请求:

$getheader = array(
    "Accept: text/html, application/xhtml+xml, */*",    
    "Accept-Language: en-US",
    "User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)",   
    "Accept-Encoding: gzip, deflate",
    "Host: mysite.com",
    "Connection: Keep-Alive"    
);


curl_setopt($ch, CURLOPT_URL, 'http://mysite.com');
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $getheader);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt'); //read from the cookie
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

curl_exec($ch);

它工作正常但是Header按照以下错误顺序发送:

GET http://mysite.com/ HTTP/1.1
Cookie: remember_me=1; id=9089018083 <------ this line should be at the end
Accept: text/html, application/xhtml+xml, */*
Accept-Language: en-US
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Accept-Encoding: gzip, deflate
Host: mysite.com
Connection: Keep-Alive

cookie应该在标题之后发送(正如Web浏览器所做的那样)但在我的情况下我不知道出了什么问题。能帮忙吗?

由于

1 个答案:

答案 0 :(得分:2)

为什么“应该”在底部?

HTTP RFC规定了以下内容:

  • 标题键的大小写没有重要性
  • 标题的顺序没有重要性

所有这些都在RFC 2616(HTTP 1.1)中明确说明:http://www.ietf.org/rfc/rfc2616.txt,第31页:

  

具有不同字段名称的标题字段的顺序      收到的并不重要。但是,发送是“好习惯”      首先是general-header字段,然后是request-header或response-      标题字段,以实体标题字段结尾。

因此,虽然curl没有产生你期望的输出,但它没有做任何错误的。顺序是任意的,curl之所以这样做是因为它会处理cookie jar first ,然后允许你使用HEADERS设置覆盖你最喜欢的任何标题。

所以,实际上,如果你的代码在标题顺序上挑剔,你需要教你的代码不要担心它们,因为各种各样的浏览器会发送不同的标题顺序。最终,要接受宽大,严格排放。