为什么 php 中 curl 调用后 set-cookie 的区别


Why the difference of set-cookie after curl call in php

>我有两页

http://site.aspx?page=AddressData2&AddressID=298587,466579,66052

http://site.aspx?page=AddressData2&ShowPanel=EID

第二个链接旨在维护访问后存储在第一个链接中的相同cookie/会话信息。

我通过以下方式存储了第一个cookie:

$cookies    =array(
        $cookies[0]=>$cookies[1],
        "__utma"=>"250300755.603693956.1425821004.1425827777.1425854702.4",
        "__utmb"=>"250300755",
        "__utmc"=>"250300755",
        "__utmz"=>"250300755.1425821004.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)",
        "style"=>"A--"
);
$formattedCookies='';
foreach ($cookies as $key => $value) {
    $formattedCookies.=$key."=".$value."; ";
}
$formattedCookies   .=" path=/; HttpOnly ";

它密切模拟您将在浏览器的 Cookie 存储中获得的相同 Cookie。

但是,在我以与第一个链接相同的方式访问第二个链接后

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER  ,1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url_search);
// Execute
$result=curl_exec($ch);

并且仅在另外,对于访问第二个链接的 curl 调用,我在 curl_setopt($ch, CURLOPT_HEADER ,1); 下添加此行以设置我之前制作的 cookie,

curl_setopt($ch2, CURLOPT_COOKIE,$formattedCookies);

然而,结果却大不相同。

在第一个链接中,curl_exec($ch2)的标头结果如下所示:

HTTP/1.1 302 Found
Date: Sun, 08 Mar 2015 23:28:34 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Location: site.aspx?page=AddressData2&AddressID=298587,466579,66052
Set-Cookie: ASP.NET_SessionId=grrmvt55muepmsqruxxqwfrl; path=/; HttpOnly
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 201
HTTP/1.1 200 OK
Date: Sun, 08 Mar 2015 23:28:34 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Set-Cookie: ASP.NET_SessionId=scmi1gvhrw5pwh45nv0hw1j3; path=/; HttpOnly
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 17170

而在第二个链接中,结果如下所示:

HTTP/1.1 302 Found
Date: Mon, 09 Mar 2015 00:01:19 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Location: site.aspx?page=error
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 156
HTTP/1.1 200 OK
Date: Mon, 09 Mar 2015 00:01:19 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Set-Cookie: ASP.NET_SessionId=dssnqq45hytyvy55kl3na455; path=/; HttpOnly
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 16335

如您所见,Set-Cookie 和 Location 之间存在很大差异,在第二个链接卷曲结果中,该位置成为错误页面,而标头的第一部分不存在 set-cookie。

想知道我哪里做错了?

CURLOPT_COOKIESESSION不是

设置请求Cookie:标头的选项。 CURLOPT_COOKIE是。也就是说,path=/; HttpOnly永远不应该成为其中的一部分。

由于第二个 URI 期望会话 cookie 存在于请求中,而不是因为您未能设置它,它会将您重定向到错误消息页面。

不要尝试手动处理 Cookie,而是使用单个卷曲句柄CURLOPT_COOKIEJAR并为两个请求设置了选项。