I am accessing images from another website. I am getting this Error:
"failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request " error when 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开发者_JS百科=='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);
}
I think preg_replace make more better sense as it will work with latest versions of the PHP as ereg_replace didn't worked for me being deprecated
$url = preg_replace("/ /", "%20", $url);
I had the same problem, but it was solve by
$url = str_replace(" ", "%20", $url);
Thanks Cello_Guy for the post.
The only issue I can think of is spaces being in the url, most likely in the file name. All spaces in a url need to be converted to their proper 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 to problems.
Just use the str_replace()
to replace the spaces (" ") for their proper encoding ("%20")
It looks like this:
$url = str_replace(" ", "%20", $url);
For more information on the str_replace()
check out The PHP Manual.
Use the function rawurlencode()
Encodes the given string according to » RFC 3986.
http://php.net/manual/ru/function.rawurlencode.php
Even a trailing blank in the url can cause php file($url) to fail. In recent versions of php or apache even a trailing blank in the url will cause the error. So the url appears to work in a browser because the browser knows enough to %20 the trailing blank or ignore it. That was my error anyway.
Older LAMP allowed it. (ie. same code ran ok). Easy fix.
It seems that the URL has some spaces or other special characters, you need to encode it, use urlencode() function
精彩评论