对于名称中包含空格的文件,file_exists()返回false


file_exists() return false for files with whitespaces in the name

我有这个代码:

$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

有什么建议吗?

问题是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')){
...

您可以在这里找到许多其他方法:如何使用PHP检查远程文件是否存在?

试试这个:

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);