PHP getimagesize - Failed to open stream. Bad request

2.8k views Asked by At

I am getting the following error:

getimagesize(https://static1.squarespace.com/static/570d03d02b8dde8b2642afca/570f74e87c65e4819dec6812/57272dbfb6aa606f78a5d8b5/1470397291105/4XTRYCK3.jpg): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request

The image opens without problems in my browser.

Does anyone understand why this fails?

2

There are 2 answers

1
Eric_WVGG On BEST ANSWER

Squarespace is rejecting any connection where the User-Agent header is not a web browser. This includes CURL and getimagesize.

You can set the user-agent header by inserting this into your code:

ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)');
0
Mark Bench On

In my case (clearly not the same as the OP based on their URL) there were two problems.

The first was that the URL I was being given was HTTP, but the browser would successful redirect to HTTPS while my getimagesize() would fail with the given error. I had to replace "http" with "https" in my URL.

$url = "http://test.com/file name.jpg";
$url = preg_replace('/^http:/', 'https:', $url);

The second was that the URL I was given had a space in it. I had to encode the space as %20.

$url = (dirname($url) . '/'. rawurlencode(basename($url)));
Final URL: https://test.com/file%20name.jpg

With those two replacements, the call to getimagesize() was successful.