我需要检查一个文件是否存在,但我不知道它的扩展名。
例如,我希望执行以下操作:
if(file_exists('./uploads/filename')):
// do something
endif;
当然,这不起作用,因为它没有扩展名。扩展名将是jpg、jpeg、png或gif中的一个。
有没有不使用循环的方法来实现这个?
我需要检查一个文件是否存在,但我不知道它的扩展名。
例如,我希望执行以下操作:
if(file_exists('./uploads/filename')):
// do something
endif;
当然,这不起作用,因为它没有扩展名。扩展名将是jpg、jpeg、png或gif中的一个。
有没有不使用循环的方法来实现这个?
function resolve($name) {
// reads informations over the path
$info = pathinfo($name);
if (!empty($info['extension'])) {
// if the file already contains an extension returns it
return $name;
}
$filename = $info['filename'];
$len = strlen($filename);
// open the folder
$dh = opendir($info['dirname']);
if (!$dh) {
return false;
}
// scan each file in the folder
while (($file = readdir($dh)) !== false) {
if (strncmp($file, $filename, $len) === 0) {
if (strlen($name) > $len) {
// if name contains a directory part
$name = substr($name, 0, strlen($name) - $len) . $file;
} else {
// if the name is at the path root
$name = $file;
}
closedir($dh);
return $name;
}
}
// file not found
closedir($dh);
return false;
}
使用方法:
$file = resolve('/var/www/my-website/index');
echo $file; // will output /var/www/my-website/index.html (for example)
希望能对某些人有所帮助, Ioan
glob
函数也可以与类似于Bash的花括号扩展一起使用:glob("./uploads/filename.{jpg,jpeg,png,gif}", GLOB_BRACE)
。 - Gumbo