PHP: Redirection limit reached

PHP may give you the following error:

PHP Warning: file_get_contents(http://example.org/):
 failed to open stream: Redirection limit reached, aborting

This means that the URL you are accessing is telling you via a HTTP Location: header, that the data you want can be found on a different URL. This different URL tells you that the data you want can be found on another different URL. This another different URL ...

The game continues, 20 times. Then, PHP decides to stop following redirects and gives you the error.

The HTTP headers that make your client follow the Location header are:

More redirections

If you want more than the default 20 redirects allowed by PHP, you can modify the HTTP stream context by setting the max_redirects option:

<?php
$context = stream_context_create(
    array(
        'http' => array(
            'max_redirects' => 101
        )
    )
);
$content = file_get_contents('http://example.org/', false, $context);
?>

No redirection

You may also choose to not follow any redirects by setting follow_location :

<?php
$context = stream_context_create(
    array(
        'http' => array(
            'follow_location' => false
        )
    )
);
$content = file_get_contents('http://example.org/', false, $context);
?>

In this case, you will get the content of the page that causes the redirect.

Written by Christian Weiske.

Comments? Please send an e-mail. Or Reply or Like.