PHP检查文件是否存在,而不知道文件扩展名

36

我需要检查一个文件是否存在,但我不知道它的扩展名。

例如,我希望执行以下操作:

if(file_exists('./uploads/filename')):
 // do something
endif;

当然,这不起作用,因为它没有扩展名。扩展名将是jpg、jpeg、png或gif中的一个。

有没有不使用循环的方法来实现这个?

2个回答

74

你需要使用glob()函数

$result = glob ("./uploads/filename.*");

并查看 $result 是否包含任何内容。


21
glob函数也可以与类似于Bash的花括号扩展一起使用:glob("./uploads/filename.{jpg,jpeg,png,gif}", GLOB_BRACE) - Gumbo
是否有办法在文件没有扩展名的情况下也能检索到该文件? - NaturalBornCamper

9
我有同样的需求,并尝试使用glob函数,但这个函数似乎不太可移植:
请参阅http://php.net/manual/en/function.glob.php中的注释:
注意:此函数在某些系统上不可用(例如旧版Sun OS)。
注意:GLOB_BRACE标志在某些非GNU系统上不可用,如Solaris。
它比opendir还要慢,请查看:哪个更快:glob()还是opendir()
因此,我编写了一个代码片段函数来完成相同的任务:
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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接