11

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 code that does this?

GeoffreyF67
  • 11,061
  • 11
  • 46
  • 56

3 Answers3

16
$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
}
Brian Fisher
  • 23,519
  • 15
  • 78
  • 82
  • Cool - is there a way to tell where it wants to redirect to? – GeoffreyF67 Jan 09 '09 at 06:13
  • Try normal cURL to it... it should direct you to where it wants you to go to. – alex Jan 09 '09 at 06:39
  • Good answer, which should cover almost all possible cases. I believe 303 and 307 constitute redirects as well, although they are far less common - I've only seen them used in spec docs, not the real world. – Chris Burgess Jan 10 '09 at 09:51
  • It's worth noting that you will want to add `curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);` if you want to do something like `$data = curl_exec($ch)` instead of sending the results to the browser. – degenerate Feb 17 '14 at 03:55
6

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;
    }
GeoffreyF67
  • 11,061
  • 11
  • 46
  • 56
3

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!

earino
  • 2,885
  • 21
  • 20
  • Actually, you could use the javascript engine that mozilla has although I can't remember it's name at the moment. But yeah, you're right in that curl would not catch javascript redirection. – GeoffreyF67 Jan 27 '09 at 05:48