我需要查看CDN中是否存在特定的图片。
我尝试了以下方法,但没有成功:
if (file_exists(http://www.example.com/images/$filename)) {
echo "The file exists";
} else {
echo "The file does not exist";
}
即使图片存在或不存在,它总是显示"文件已存在"。我不确定为什么它不起作用...
至少需要将文件名用引号括起来(作为字符串):
if (file_exists('http://www.mydomain.com/images/'.$filename)) {
… }
另外,请确保正确验证$filename
。只有在您的PHP配置中激活allow_url_fopen
时,它才能起作用。
if (file_exists('http://www.mydomain.com/images/'.$filename)) {}
$src = 'http://www.mydomain.com/images/'.$filename;
if (@getimagesize($src)) {
getimagesize(http://www.mydomain.com/images/filename.png) [function.getimagesize]: failed
),它将返回false。@getimagesize('//path/to/image.jpg')
是无法工作的)。 - thdoan可以尝试这样做:
$file = '/path/to/foo.txt'; // 'images/'.$file (physical path)
if (file_exists($file)) {
echo "The file $file exists";
} else {
echo "The file $file does not exist";
}
好的,file_exists
函数并不能判断文件是否存在,它只能判断路径是否存在。 ⚡⚡⚡⚡⚡⚡⚡
因此,如果要检查是否为文件,则应该将 is_file
与 file_exists
结合使用,以了解路径后面是否实际上有一个文件,否则 file_exists
对于任何现有路径都会返回true
。
这是我使用的函数:
function fileExists($filePath)
{
return is_file($filePath) && file_exists($filePath);
}
file_exists( ... )
函数可能被命名错误了。无论如何,你的函数是多余的。你可以把现有的is_file( ... )
用另一个名称保存,它将与你的函数一样工作。祝大家节日快乐! - s3c以下是检查文件是否存在的最简单方法:
if(is_file($filename)){
return true; //the file exist
}else{
return false; //the file does not exist
}
$file = './images/image.jpg';
if (file_exists($file)) {}
经常会忘记加上“.”,导致文件显示为不存在,但实际上文件是存在的。
public static function is_file_url_exists($url) {
if (@file_get_contents($url, 0, NULL, 0, 1)) {
return 1;
}
return 0;
}
is_file
和file_exists
之间有一个重大区别。
is_file
返回(常规)文件的真值:
如果文件名存在且为常规文件,则返回TRUE,否则返回FALSE。
file_exists
对于文件和目录都返回真值:
如果由文件名指定的文件或目录存在,则返回TRUE;否则返回FALSE。
注意: 请查看这个stackoverflow问题以获取更多关于此主题的信息。
你需要使用绝对路径来检查文件是否存在。
$abs_path = '/var/www/example.com/public_html/images/';
$file_url = 'http://www.example.com/images/' . $filename;
if (file_exists($abs_path . $filename)) {
echo "The file exists. URL:" . $file_url;
} else {
echo "The file does not exist";
}
如果您正在编写CMS或PHP框架相关的内容,那么据我所知,它们都定义了文档根路径的常量。
例如,WordPress使用ABSPATH,该常量可以全局使用,可用于使用您的代码在服务器上处理文件以及站点URL。
WordPress示例:
$image_path = ABSPATH . '/images/' . $filename;
$file_url = get_site_url() . '/images/' . $filename;
if (file_exists($image_path)) {
echo "The file exists. URL:" . $file_url;
} else {
echo "The file does not exist";
}
我在这里做了额外的努力 :). 因为这段代码不需要太多维护并且非常稳定,所以我会使用简写 if 语句来编写它:
$image_path = ABSPATH . '/images/' . $filename;
$file_url = get_site_url() . '/images/' . $filename;
echo (file_exists($image_path))?'The file exists. URL:' . $file_url:'The file does not exist';
简写的IF语句解释:
$stringVariable = ($trueOrFalseComaprison > 0)?'String if true':'String if false';
file_exists
操作,可能会非常缓慢。 - crmpicco