403 Forbidden when using PHP file_get_contents

Will Fong's Avatar

Will Fong

08 Jul, 2012 09:03 PM

Hi. I wrote a PHP script to grab some of my drops. It recently stopped working with this error message:

[Sun Jul 08 13:49:32 2012] [error] [client 67.183.142.XXX] PHP Warning: file_get_contents(http://d.pr/i/vkVo+): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden\r\n in xxx

It was working a few months ago, but I haven't been using it in a while so I don't know what changed. The code looks like this:

$url = "http://d.pr/i/vkVo"; file_get_contents( $url.'+' );

If I use wget to grab the file, the URL works as expected. I think it's something PHP isn't doing, but I the only error I get is a 403. Any guidance would be appreciated.

Thanks!
-will

  1. 2 Posted by Marcel on 10 Jul, 2012 05:32 AM

    Marcel's Avatar

    Hi,

    I think it is a protection. You have to set the userclient otherwise the webserver sent a 403.
    Maybe you should try curl to make your operation.
    You can try this function to check if an other status code will appear:

    function url_exists($url) {
      $ch = curl_init($url);
      curl_setopt($ch,CURLOPT_HEADER,true);
      curl_setopt($ch,CURLOPT_POST,false);
      curl_setopt($ch,CURLOPT_FAILONERROR,true);
      curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        // set user agent
        $userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.53.11 (KHTML, like Gecko) Version/5.1.3";
        curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
        curl_exec($ch);
      $curlInfo = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
      curl_close ($ch);
    
      if ($curlInfo != 200 && $curlInfo != 302 && $curlInfo != 304) {
         return false;
      } else {
          return true;
      }
    }
    
  2. 3 Posted by Will F on 11 Jul, 2012 06:02 AM

    Will F's Avatar

    Hi Marcel,

    I tried adding the User-Agent and got the same reply.

    I'm wondering if it's the Location: redirect that is confusing file_get_contents. In any case, I'm going to just use wget to grab the file. I don't want to mess with it anymore :)

    Thanks for your help!

    -will

  3. Bruno de Carvalho closed this discussion on 20 Jul, 2012 04:33 AM.

Comments are currently closed for this discussion. You can start a new one.