file_exists()对名称中带有空格的文件返回false

时间:2015-03-24 15:15:21

标签: php file-exists

我有这段代码:

$url     = 'http://www.bgelectronics.eu/image/cache/data/cantell kabeli /14222-228x228.jpg';
$headers = get_headers($url, true);
var_dump($headers);

由于文件名中的空格,这会返回丢失文件的错误:

array(6) { [0]=> string(34) "HTTP/1.1 500 Internal Server Error" ["Date"]=>     
string(29) "Tue, 24 Mar 2015 16:11:18 GMT" ["Server"]=> string(6) "Apache" 
["Content-Length"]=> string(3) "677" ["Connection"]=> string(5) "close" 
["Content-Type"]=> string(29) "text/html; charset=iso-8859-1" } file size:677

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

问题是file_exists()用于文件系统,而不是http。您需要使用服务器目录路径。如果它与您的代码在同一服务器上,它应该看起来像:

if(file_exists('image/cache/data/cantell kabeli /202441-500x500.jpg')){
....

如果在远程服务器上,请尝试:

if(file_get_contents('http://www.bgelectronics.eu/image/cache/data/cantell kabeli /202441-500x500.jpg')){
...

您可以在此处找到许多其他方式:How can one check to see if a remote file exists using PHP?

答案 1 :(得分:0)

试试这个:

copy('http://www.bgelectronics.eu/image/cache/data/cantell kabeli /202441-500x500.jpg', '/image.jpeg');

如果没有,请使用file_get_contents

//Get the file
$content = file_get_contents("http://www.bgelectronics.eu/image/cache/data/cantell kabeli /202441-500x500.jpg");
//Store in the filesystem.
$fp = fopen("/location/to/save/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);