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

时间:2022-05-04 23:45:19

You get the current include path in PHP by using get_include_path()

使用get_include_path()获取PHP中的当前包含路径

I am wondering what is the lightweight way to check if the file can be included without issuing a PHP error. I am using Yii framework and I want to an import without issuing PHP error, but I fail.

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

2 个解决方案

#1


9  

Before PHP 5.3.2 you can split the path and check each path in a loop:

在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

#2


32  

As of PHP 5.3.2, you can use

从PHP 5.3.2开始,您可以使用

which will

Returns a string containing the resolved absolute filename, or FALSE on failure.

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

Example from Manual:

 var_dump(stream_resolve_include_path("test.php"));

The above example will output something similar to:

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

 string(22) "/var/www/html/test.php"

#1


9  

Before PHP 5.3.2 you can split the path and check each path in a loop:

在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

#2


32  

As of PHP 5.3.2, you can use

从PHP 5.3.2开始,您可以使用

which will

Returns a string containing the resolved absolute filename, or FALSE on failure.

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

Example from Manual:

 var_dump(stream_resolve_include_path("test.php"));

The above example will output something similar to:

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

 string(22) "/var/www/html/test.php"