PHP - 使用 cURL 获得重定向后的最终 URL 状态

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 进行此检查,它们的状态均为 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 选项,那么您必须确保正确分析 headers 以获得状态。 从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;
 }