如何检查包含路径下是否存在文件?

Pen*_*m10 13 php yii

您可以使用PHP获取当前包含路径 get_include_path()

我想知道什么是轻量级方法来检查是否可以包含文件而不发出PHP错误.我正在使用Yii框架,我想导入而不发出PHP错误,但我失败了.

Gor*_*don 32

从PHP 5.3.2开始,您可以使用

会的

返回包含已解析的绝对文件名的字符串,如果失败则返回FALSE.

手册示例:

 var_dump(stream_resolve_include_path("test.php"));
Run Code Online (Sandbox Code Playgroud)

上面的例子将输出类似于:

 string(22) "/var/www/html/test.php"
Run Code Online (Sandbox Code Playgroud)


Emi*_*röm 9

在PHP 5.3.2之前,您可以拆分路径并检查循环中的每个路径:

$find = 'file.php'; //The file to find
$paths = explode(PATH_SEPARATOR, get_include_path());
$found = false;
foreach($paths as $p) {
  $fullname = $p.DIRECTORY_SEPARATOR.$find;
  if(is_file($fullname)) {
    $found = $fullname;
    break;
  }
}
//$found now contains the file to be included, or false if not found
Run Code Online (Sandbox Code Playgroud)