Could not open stream: HTTP request failed! Invalid HTTP / 1.1 400 request

I am accessing images from another site. I get โ€œCould not open stream: HTTP request failed! HTTP / 1.1 400 Bad Request errorโ€ while copying โ€œsome (not all)โ€ images. here is my code.

$img=$_GET['img']; //another website url $file=$img; function getFileextension($file) { return end(explode(".", $file)); } $fileext=getFileextension($file); if($fileext=='jpg' || $fileext=='gif' || $fileext=='jpeg' || $fileext=='png' || $fileext=='x-png' || $fileext=='pjpeg'){ if($img!=''){ $rand_variable1=rand(10000,100000); $node_online_name1=$rand_variable1."image.".$fileext; $s=copy($img,"images/".$node_online_name1); 

}

+8
source share
4 answers

I think that preg_replace understands better, since it will work with the latest versions of PHP, since ereg_replace did not work out of date for me

 $url = preg_replace("/ /", "%20", $url); 
+14
source

I had the same problem, but it was solved

 $url = str_replace(" ", "%20", $url); 

Thanks to Cello_Guy for the message.

+10
source

The only problem I can think of is the spaces found in the URL, most likely in the file name. All spaces in the URL must be converted to their correct encoding, which is% 20.

If you have a file name like this:

" http://www.somewhere.com/images/img 1.jpg"

You would get the above error, but with this:

" http://www.somewhere.com/images/img%201.jpg "

You should have problems.

Just use str_replace() to replace spaces (") for their proper encoding ("% 20 ")

It looks like this:

 $url = str_replace(" ", "%20", $url); 

For more information on str_replace() check out the PHP Manual .

+4
source

Use the rawurlencode() function

Encodes this string in accordance with RFC 3986.

http://php.net/manual/ru/function.rawurlencode.php

+1
source

Source: https://habr.com/ru/post/650462/


All Articles