本文介绍了PHP:可以包含file_exists()表示不存在的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



但是,在我设置包含路径后, 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,数组(
$ include_path,
get_include_path()
))
);
//引导程序文件位于:path / to / some / directory / bootstrap.php。
$ bootstrap ='bootstrap.php';

//返回bool(true)。
var_dump(file_exists($ include_path。'/'。$ bootstrap));
//返回bool(false)。
var_dump(file_exists($ bootstrap));

//这让我相信包含路径没有正确设置。
//但确实如此。接下来就是让我困惑的事情。

require_once $ bootstrap;
//不仅没有错误,而且文件包含成功!

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

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



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

解决方案

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


In my script, I set the include path (so another part of the application can include files too), check that a file exists, and include it.

However, after I set the include path, file_exists() reports that the file does not exist, yet I can still include the same file.

<?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!

I can edit the include path and include files without providing the absolute filepath, but I cannot check whether they exist or not. This is really annoying as every time a file that does not exist is called, my application results in a fatal error, or at best a warning (using include_once()).

Turning errors and warnings off is not an option, unfortunately.

Can anyone explain what is causing this behaviour?

解决方案

file_exists does nothing more than say whether a file exists (and the script is allowed to know it exists), resolving the path relative to the cwd. It does not care about the include path.

这篇关于PHP:可以包含file_exists()表示不存在的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 14:08