我通过PHP curl_exec请求网址时收到302错误消息,但手动执行时获得了代码200。什么可能是使结果不同的差异?
假设我在服务器中有以下代码:
$url = "http://localhost/circle/my_request/susan?confirm_key=c429d674e36ffe1a4f87fd5a17a0200dcfff0884e8bb3801d2a7d559dcc8d8cd1416295160";
$ch = @curl_init($url);
@curl_setopt($ch, CURLOPT_HEADER, true);
@curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
@curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Circle)");
@curl_setopt($ch, CURLOPT_TIMEOUT,60);
$s = @curl_exec($ch);
$curl_info = @curl_getinfo($ch);
$http_code = $curl_info['http_code'];
在这种情况下,$ http_code == 302,或者重定向请求的URL。但是当我手动将URL放到浏览器中时,它没有进行重定向,并把我带到了正确的位置。
我错过了什么吗?为什么这2个请求的结果不同?
提前致谢
-----------附加信息----
您好我在CURLOPT_FOLLOWLOCATION选项设置为true的情况下重新运行脚本,并得到以下输出:
HTTP/1.1 302 Found Date: Tue, 18 Nov 2014 14:36:37
GMT Server: Apache/2.4.4 (Win64)
PHP/5.4.12 X-Powered-By: PHP/5.4.12
Set-Cookie: PHPSESSID=92t2db5qalq4ajie0ols03hik6;
path=/; HttpOnly Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate,
post-check=0, pre-check=0 Pragma: no-cache X-Account-Management-Status: none
Location: http://somehost.com/circle Content-Length: 0
Content-Type: text/html HTTP/1.1
301 Moved Permanently Date: Tue, 18 Nov 2014 14:36:37
GMT Server: Apache/2.4.4 (Win64)
PHP/5.4.12 Location: http://somehost.com/circle/
Content-Length: 232 Content-Type: text/html;
charset=iso-8859-1 HTTP/1.1 200 OK Date: Tue,
18 Nov 2014 14:36:37 GMT Server: Apache/2.4.4 (Win64)
PHP/5.4.12 X-Powered-By: PHP/5.4.12
Set-Cookie: PHPSESSID=hk02sg1327eq78khbka0sf6pk6;
path=/; HttpOnly Expires: Thu, 19 Nov 1981 08:52:00
GMT Cache-Control: no-store, no-cache, must-revalidate,
post-check=0, pre-check=0 Pragma: no-cache X-Account-Management-Status: none
Transfer-Encoding: chunked Content-Type: text/html; charset=utf-8
我不确定它的内容,但我猜它被重定向到http://somehost.com/circle然后转到http://somehost.com/circle。这是对的吗?
答案 0 :(得分:6)
可能是脚本使用重定向检查cookie或可能是其他功能。
您可以在$s
输出中看到重定向网址。只需将echo $s;
插入脚本的末尾即可。
您也可以设置CURLOPT_FOLLOWLOCATION,然后在自动模式下通过重定向来卷曲。
答案 1 :(得分:0)
尝试添加更多选项
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);