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

Lee*_*Lee 30 php file-extension file-exists

我需要检查文件是否存在但我不知道扩展名.

IE我想做:

if(file_exists('./uploads/filename')):
 // do something
endif;
Run Code Online (Sandbox Code Playgroud)

当然,因为它没有扩展,所以不会工作.扩展名为jpg,jpeg,png,gif

没有做循环的任何想法吗?

Pek*_*ica 59

你必须做一个 glob():

$result = glob ("./uploads/filename.*");
Run Code Online (Sandbox Code Playgroud)

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

  • `glob`也可以与类似bash的大括号扩展一起使用:`glob("./ uploads/filename.{jpg,jpeg,png,gif}",GLOB_BRACE)`. (13认同)

小智 7

我有同样的需求,并尝试使用 glob 但此功能似乎不可移植:

请参阅http://php.net/manual/en/function.glob.php 中的注释:

注意:此功能在某些系统上不可用(例如旧的 Sun 操作系统)。

注意: 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;
}
Run Code Online (Sandbox Code Playgroud)

用法 :

$file = resolve('/var/www/my-website/index');
echo $file; // will output /var/www/my-website/index.html (for example)
Run Code Online (Sandbox Code Playgroud)

希望可以帮助某人,Ioan