How to get final URL after following HTTP redirections in pure PHP?

后端 未结 5 2015
有刺的猬
有刺的猬 2020-11-29 03:41

What I\'d like to do is find out what is the last/final URL after following the redirections.

I would prefer not to use cURL. I would like t

5条回答
  •  北海茫月
    2020-11-29 04:25

    function getRedirectUrl ($url) {
        stream_context_set_default(array(
            'http' => array(
                'method' => 'HEAD'
            )
        ));
        $headers = get_headers($url, 1);
        if ($headers !== false && isset($headers['Location'])) {
            return $headers['Location'];
        }
        return false;
    }
    

    Additionally...

    As was mentioned in a comment, the final item in $headers['Location'] will be your final URL after all redirects. It's important to note, though, that it won't always be an array. Sometimes it's just a run-of-the-mill, non-array variable. In this case, trying to access the last array element will most likely return a single character. Not ideal.

    If you are only interested in the final URL, after all the redirects, I would suggest changing

    return $headers['Location'];
    

    to

    return is_array($headers['Location']) ? array_pop($headers['Location']) : $headers['Location'];
    

    ... which is just if short-hand for

    if(is_array($headers['Location'])){
         return array_pop($headers['Location']);
    }else{
         return $headers['Location'];
    }
    

    This fix will take care of either case (array, non-array), and remove the need to weed-out the final URL after calling the function.

    In the case where there are no redirects, the function will return false. Similarly, the function will also return false for invalid URLs (invalid for any reason). Therefor, it is important to check the URL for validity before running this function, or else incorporate the redirect check somewhere into your validation.

提交回复
热议问题