3

I have programmed a simple content-user, that uses file_get_contents, but unfortunately for my IP the site now gives a 302 error that forwards to an image. For all other users the normal site is viewable.

How do I rewrite the get_contents so it will just download the content of the website and not actually follow the redirect?

$html = file_get_contents("http://www.site.net/");
Dennis
  • 2,866
  • 7
  • 32
  • 49

3 Answers3

21

You need to create a context:

$context = stream_context_create(
    array (
        'http' => array (
            'follow_location' => false // don't follow redirects
        )
    )
);
$html = file_get_contents('http://www.site.net/', false, $context);

See the manual:

With that said, it's highly likely that there is no content left on the page. It's not impossible to serve a 302 header and serve an HTTP body as well, but it's decidedly unorthodox.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • 1
    Remember, 'follow_location' is only available as of PHP 5.3.4 (which everyone should be running something newer than that anyway.) Also a "max_redirects => 0" inside the inner array is necessary (see example #2 on http://php.net/manual/en/context.http.php) – Eric Caron Aug 01 '12 at 20:17
-1

I encountered such a problem accessing Google Drive content via the direct link.

NICE WAY: With the code below it worked again:

//Any google url. Thsi example is fake for Google Drive direct link.
$url = "https://drive.google.com/uc?id=0BxQKKJYjuNElbFBNUlBndmVHHAj";

$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);  
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 3);     
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$html = curl_exec($ch);
curl_close($ch);

echo $html;

I tested it today, 03/19/2018

WRONG WAY: After calling file_get_contents returned 302 Moved temporarily

//Any google url. Thsi example is fake for Google Drive direct link.
$url = "https://drive.google.com/uc?id=0BxQKKJYjuNElbFBNUlBndmVHHAj";
$html = file_get_contents($url);
echo $html; //print none because error 302.
Sergio Cabral
  • 6,490
  • 2
  • 35
  • 37
-1

There is no content there. The redirect happens in the HTTP response before any content would be sent.

The server decides what you get to see (or not).

Oliver Salzburg
  • 21,652
  • 20
  • 93
  • 138
  • The redirect happens with HTTP response headers. However, a misconfigured server could send output, even if it is sending a new Location together with the response code 302. – AndersTornkvist May 15 '11 at 15:30
  • 1
    **This answer is incorrect** (for the avoidance of any doubt). As @Oliver says, it's not safe to assume that no content is sent with a 302. – John Mar 31 '17 at 06:01