PHP:可以包含file_exists()表示不存在的文件

时间:2010-02-25 01:56:35

标签: php file path include require

在我的脚本中,我设置了包含路径(因此应用程序的另一部分也可以包含文件),检查文件是否存在,并包含它。

但是,在我设置包含路径后,file_exists()报告该文件不存在,但我仍然可以包含相同的文件。

<?php
  $include_path = realpath('path/to/some/directory');
  if(!is_string($include_path) || !is_dir($include_path))
  {
    return false;
  }
  set_include_path(
    implode(PATH_SEPARATOR, array(
      $include_path,
      get_include_path()
    ))
  );
  // Bootstrap file is located at: "path/to/some/directory/bootstrap.php".
  $bootstrap = 'bootstrap.php';

  // Returns "bool(true)".
  var_dump(file_exists($include_path . '/' . $bootstrap));
  // Returns "bool(false)".
  var_dump(file_exists($bootstrap));

  // This led me to believe that the include path was not being set properly.
  // But it is. The next thing is what puzzles me.

  require_once $bootstrap;
  // Not only are there no errors, but the file is included successfully!

我可以编辑包含路径并包含文件而不提供绝对文件路径,但我无法检查它们是否存在。这真的很烦人,因为每次调用不存在的文件时,我的应用程序都会导致致命错误,或者最多会出现警告(使用include_once())。

不幸的是,关闭错误和警告不是一种选择。

任何人都可以解释造成这种行为的原因吗?

2 个答案:

答案 0 :(得分:3)

file_exists只是说文件是否存在(并且允许脚本知道它存在),解析相对于cwd的路径。它并不关心包含路径。

答案 1 :(得分:0)

是这是实现此

的最简单方法
$file_name = //Pass File name 
if ( file_exists($file_name) )
            {
                echo "Exist";
            }
        else
            {
                echo "Not Exist";
            }