2

Whenever I visit this URL in my browser, it works fine and the file uploads to my account:

http://api.imgur.com/2/upload.json?key=<my key>&image=<url to image>

But when I attempt to retrieve it in PHP with something like file_get_contents, I get this error message:

Warning: file_get_contents(<URL>): failed to open stream:
HTTP request failed! HTTP/1.1 400 Bad Request

You can see an example with this URL: http://api.imgur.com/2/upload.json?key=&image=https://www.google.com/images/srpr/logo3w.png

Edit: I also attempted to use a user agent but to no avail.

UserIsCorrupt
  • 4,837
  • 15
  • 38
  • 41

2 Answers2

1

Bad request mostly means that one the parameters you gave are wrong. What I always do is test the API by sending a request from my webbrowser. I test the URL and check the result.

Jordi Kroon
  • 2,607
  • 3
  • 31
  • 55
  • I did this, I checked that URL in my browser and it worked fine, then I attempted to use retrieve it in PHP and got that error. – UserIsCorrupt Jan 05 '13 at 02:33
1

Use curl, it could be simply url_fopen is disabled in your php

it also gives you full control to change user-agent

Use this code:

function getContentWithCurl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // Set so curl_exec returns the result instead of outputting it.
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT , ">>>PUT_USER_AGENT_HERE<<<" );
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5);

        // Get the response and close the channel.
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

getContentWithCurl( "YOUR_URL_HERE" );

Shehabic
  • 6,787
  • 9
  • 52
  • 93
  • This worked, I'm not too familiar with `curl` but I've been meaning to explore it more; this is a reason to start, I guess. Thanks! – UserIsCorrupt Jan 05 '13 at 03:01
  • Why does curl work even with bad request and file_get_contents doesn't? – Angel Jan 05 '13 at 03:06
  • If allow_url_fopen = Off file_get_contents is allowed to open local files only, I think this is the case here – Shehabic Jan 05 '13 at 03:08