[英]PHP - Using cURL to get the final URL status after redirect
在某些可能的重定向之后,我正在使用此函数来获取最终URL的状态:
function getUrlStatus($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$redirectURL = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
curl_close($ch);
if($httpStatus >= 300 && $httpStatus < 400) {
getUrlStatus($redirectURL);
} else {
return $httpStatus;
}
}
如果我检查的第一个URL未重定向,则可以正常工作并显示状态,但是如果正在检查重定向的URL(因此,递归调用getUrlStatus
函数),结果似乎为NULL
:
var_dump(getUrlStatus($url)); // NULL
我正在检查多个URL,所有URL的状态均为307,因此它们都再次调用了该函数,因此显示NULL
。 请告知我我在做什么错。 谢谢!
您正在寻找CURLOPT_FOLLOWLOCATION
TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
来自: http : //docs.php.net/manual/da/function.curl-setopt.php
如果您不打算使用选项CURLOPT_FOLLOWLOCATION
则必须确保正确分析标题以获取状态。 从http://php.net/manual/en/function.curl-getinfo.php
您可以看到CURLINFO_HTTP_CODE - The last response code.(...)
意味着:可以有多个状态代码。 即使用http://airbrake.io/login
发送了两个:
HTTP/1.1 301 Moved Permanently
(...)
HTTP/1.1 200 OK
(...)
这意味着将仅返回200,并且如果您想获得任何结果,则您的函数需要如下所示:
if($httpStatus >= 300 && $httpStatus < 400) {
return getUrlStatus($redirectURL);
} else {
return $httpStatus;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.