简体   繁体   中英

PHP - Using cURL to get the final URL status after redirect

I am using this function to get the status of the final URL after some possible redirects:

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;
        }
    }

If the first URL I check is not redirected, this works fine and displays the status, but if there is a redirected URL which is being checked (so the getUrlStatus function is called recursively), the result seems to be NULL :

var_dump(getUrlStatus($url));   //   NULL

I am doing this check for multiple URLs and all of them have the status 307, so they are all calling again the function so NULL is being displayed. Please advise what am I doing wrong. Thanks!

You're looking for 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). from: http://docs.php.net/manual/da/function.curl-setopt.php

If you don't plan to use the option CURLOPT_FOLLOWLOCATION then you must make sure you're analyzign the headers correctly to get the status. From http://php.net/manual/en/function.curl-getinfo.php you can see CURLINFO_HTTP_CODE - The last response code.(...) that means: there can be more than one status code. ie with http://airbrake.io/login there are two sent:

HTTP/1.1 301 Moved Permanently
(...)

HTTP/1.1 200 OK
(...)

That means, only 200 is going to be returned, and if you want to get ANY result, your function needs to look like:

 if($httpStatus >= 300 && $httpStatus < 400) {
     return getUrlStatus($redirectURL);
 } else {
     return $httpStatus;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM