如何检查成功包含的php文件?

use*_*626 9 php include


我想检查'ad.php'中是否包含'dbas.php'.我写了代码 -

ad.php

<?php if(file_exists("dbas.php") && include("dbas.php")){
// some code will be here
}
else{echo"Database loading failed";}
?>
Run Code Online (Sandbox Code Playgroud)

我成功测试了file_exists()部分,但不知道include()是否能正常工作,因为我在localhost中尝试过,如果文件在目录中,那么它永远不会包含.因此,如果流量很大,我不知道这个代码在服务器中的表现如何.那么请告诉我我的代码是否正确?

-谢谢.

解决了:非常感谢您的回答.

Ala*_*sjo 16

如果您想要绝对确定包含该文件,则使用php的require方法更合适.file_exists仅检查文件是否存在,而不是它是否实际可读.

require如果包含失败将产生错误(您可以catch错误,请参阅Cerbrus的回答).

编辑:

但是,如果你不希望脚本如果包含未能制止,使用的方法is_readable与一起file_exists,如:

if( file_exists("dbas.php") && is_readable("dbas.php") && include("dbas.php")) {
    /* do stuff */
}
Run Code Online (Sandbox Code Playgroud)


Cer*_*rus 8

只需使用require:

try {
    require 'filename.php';
} catch (Exception $e) {
    exit('Require failed! Error: '.$e);
    // Or handle $e some other way instead of `exit`-ing, if you wish.
}
Run Code Online (Sandbox Code Playgroud)

还没有提到的东西:你可以添加一个布尔值,如:

$dbasIncluded = true;
Run Code Online (Sandbox Code Playgroud)

在您的dbas.php文件中,然后在代码中检查该布尔值.虽然通常情况下,如果文件没有正确包含,你需要php来制动,而不是渲染页面的其余部分.

  • 但这不起作用,是吗?要求抛出致命错误,这不能用try/catch捕获. (6认同)