【问题标题】:PHP check file exists without knowing the extensionPHP检查文件存在而不知道扩展名
【发布时间】:2011-03-19 05:40:32
【问题描述】:

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

我想做的IE:

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

这当然行不通,因为它没有扩展名。扩展名可以是 jpg、jpeg、png、gif

有什么想法可以在不循环的情况下做到这一点吗?

【问题讨论】:

    标签: php file-extension file-exists


    【解决方案1】:

    你必须做一个glob():

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

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

    【讨论】:

    • glob 也可以与类似 bash 的大括号扩展一起使用:glob("./uploads/filename.{jpg,jpeg,png,gif}", GLOB_BRACE)
    • 如果文件没有扩展名,还有什么方法可以检索文件?
    【解决方案2】:

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

    http://php.net/manual/en/function.glob.php的注释:

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

    注意:GLOB_BRACE 标志在某些非 GNU 系统上不可用,例如 Solaris。

    它也比opendir慢,看看:Which is faster: glob() or opendir()

    所以我做了一个 sn-p 函数来做同样的事情:

    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)
    

    希望这可以帮助某人, 伊万

    【讨论】:

      猜你喜欢
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-25
      • 2020-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多