繁体   English   中英

检查是否存在包含(或要求)

[英]Check if an include (or require) exists

在调用之前如何检查include / require_once是否存在,我尝试将其放入错误块中,但PHP不喜欢它。

我认为file_exists()会付出一些努力,但这需要整个文件路径,并且无法轻松地将相对包含传递给它。

还有其他方法吗?

我相信file_exists确实可以使用相对路径,不过你也可以尝试这些方法......

if(!@include("script.php")) throw new Exception("Failed to include 'script.php'");

...不用说,您可以将异常替换为您选择的任何错误处理方法。 这里的想法是, if语句来验证文件是否可以包括在内,以及任何错误消息通常是由输出include被用前缀它supressed @

您还可以检查包含文件中定义的任何变量,函数或类,并查看包是否有效。

if (isset($variable)) { /*code*/ }

要么

if (function_exists('function_name')) { /*code*/ }

要么

if (class_exists('class_name')) { /*code*/ }

查看stream_resolve_include_path函数,它使用与include()相同的规则进行搜索。

http://php.net/manual/en/function.stream-resolve-include-path.php

file_exists可用于检查所需文件是否存在,当它相对于当前工作目录时,因为它与相对路径一起正常工作。 但是,如果包含文件位于PATH的其他位置,则必须检查多个路径。

function include_exists ($fileName){
    if (realpath($fileName) == $fileName) {
        return is_file($fileName);
    }
    if ( is_file($fileName) ){
        return true;
    }

    $paths = explode(PS, get_include_path());
    foreach ($paths as $path) {
        $rp = substr($path, -1) == DS ? $path.$fileName : $path.DS.$fileName;
        if ( is_file($rp) ) {
            return true;
        }
    }
    return false;
}

file_exists()使用相对路径,它还会检查目录是否存在。 使用is_file()代替:

if (is_file('./path/to/your/file.php'))
{
    require_once('./path/to/your/file.php');
}

我认为正确的方法是:

if(file_exists(stream_resolve_include_path($filepath))){
  include $filepath;    
}

这是因为文档stream_resolve_include_path根据与fopen()/ include相同的规则解析“包含路径的文件名”。

有些人建议使用is_fileis_readable但这不适用于一般用例,因为在一般用法中,如果文件在file_exists返回TRUE后因某种原因被阻止或不可用,那么你需要注意一些非常难看的东西最终用户脸上的错误消息,或者您可能会在以后出现意外和无法解释的行为,可能会丢失数据等等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM