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

2022-08-30 13:20:28

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

IE 我想做的:

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

当然,这不会起作用,因为它没有扩展。扩展名将是 jpg,jpeg,png,gif

任何关于在不做循环的情况下做到这一点的想法?


答案 1

你必须做一个 glob():

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

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


答案 2

我有同样的需求,并试图使用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)

希望可以帮助某人,伊万


推荐