PHP检查文件是否存在而不是目录

时间:2012-11-19 12:15:58

标签: php

我看到file_exists()如果指向某个目录,也可以返回。检查是否只退出文件的最快方法是什么?

目前我有:

/**
 * Check if the file exists.
 *
 * @return bool
 */
public function exists() {
    if(is_null($this->_file)) return false;

    return (!is_dir($this->_file) && file_exists($this->_file)) ? true : false;
}

我发现了许多与检查文件是否以PHP格式退出相关的帖子,但没有任何内容涉及该目录以及如何最好地检查它。

这种方法可以调用1000次,所以我可以尽可能快地完成它。

3 个答案:

答案 0 :(得分:27)

您正在寻找is_file功能:

public function exists() {
    return $this->_file !== null && is_file($this->_file);
}

答案 1 :(得分:2)

public function exists() {
    return !is_dir($this->_file) && file_exists($this->_file);
}

答案 2 :(得分:1)

您可以尝试仅限文件。它是一个自定义函数,您将调用而不是file_exists函数

 function custom_file_exists($filePath)
    {
          if((is_file($filePath))&&(file_exists($filePath))){
            return true;
          }   
          return false;
    }