php - 使用 PHP 和 curl 的标题顺序

标签 php curl

我正在使用以下 PHP 代码发送带有特定 header 和 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 应该在 header 之后发送(就像网络浏览器所做的那样)但在我的情况下我不知道出了什么问题。你能帮忙吗?

谢谢

最佳答案

为什么“应该”在底部?

除其他事项外,HTTP RFC 声明:

  • header 键的大小写无关紧要
  • 标题的顺序并不重要

所有这些在RFC 2616 (HTTP 1.1) 中都说得很清楚了| : 第 31 页:

The order in which header fields with differing field names are received is not significant. However, it is "good practice" to send general-header fields first, followed by request-header or response- header fields, and ending with the entity-header fields.

因此,虽然 curl 没有产生您期望的输出,但它没有做任何错误的事情。顺序是任意的,curl 这样做的原因是因为它将首先 处理 cookie jar,然后允许您在最后使用 HEADERS 设置覆盖您喜欢的任何 header 。

所以,实际上,如果您的代码对 header 顺序很挑剔,您需要教会您的代码不要担心它们,因为各种各样的浏览器会发送不同的 header 顺序。归根结底,宽收严放。

关于php - 使用 PHP 和 curl 的标题顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16703857/

相关文章:

php - 导入 mySQL 数据 - 错误的字符集

php - 如何确保 MySQL 数据库中快速变化的数据在 PHP 脚本中准确表示?

php - SQL语法错误

php - SQL查询根据某列值获取所有记录

Docker 构建退出,退出代码为 : 1

php - 在 php 脚本仍在执行时回显消息

数组中的 PHP 最短/最长字符串长度

curl - 在:/Library/Developer/CommandLineTools/usr/bin/xcrun Failed to clone nvm repo上缺少xcrun

python - 不使用 PyCurl 的类似 Curl 的客户端证书发送 : how?

curl - Elixir HTTPoison 握手失败