How can I determine if a URL redirects in PHP?

前端 未结 3 963
我寻月下人不归
我寻月下人不归 2020-12-08 23:52

I saw someone ask a question about detecting if a URL redirects from groovy and perl but couldn\'t find anything on PHP.

Anyone know of somewhere I could find that c

相关标签:
3条回答
  • 2020-12-08 23:59

    Actually, I found this works best:

        function GetURL($URL)
        {
                $ch = curl_init($URL);
    
                curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
    
    
                curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    
                curl_exec($ch);
    
                $code = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    
                curl_close($ch);
    
                return $code;
        }
    
    0 讨论(0)
  • 2020-12-09 00:11
    $ch = curl_init('http://www.yahoo.com/');
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if (($code == 301) || ($code == 302)) {
      //This was a redirect
    }
    
    0 讨论(0)
  • 2020-12-09 00:18

    Do remember that none of the answers that are usually given for this question take into account redirection caused by javascript encoded within the returned document (or I think a meta-refresh tag in the HTML.) So it's possible that no matter what you will miss certain kinds of "redirects" when testing using this sort of code.

    Unfortunately the only way around this is to have an actual web browser hit the web page, and have the web browser modified in such a manner which it reports javascript and meta-refresh redirections.

    Cheers!

    0 讨论(0)
提交回复
热议问题