如何在PHP中捕获require()或include()的错误?

R_U*_*ser 16 php error-handling try-catch require fatal-error

我正在用PHP5编写一个需要某些文件代码的脚本.当A文件不可用时,首先会发出警告,然后抛出致命错误.当无法包含代码时,我想打印自己的错误消息.如果requeire不起作用,是否可以执行最后一个命令?以下不起作用:

require('fileERROR.php5') or die("Unable to load configuration file.");
Run Code Online (Sandbox Code Playgroud)

error_reporting(0)仅使用白色屏幕来抑制所有错误消息,而不是使用error_reporting给出PHP错误,我不想显示它.

Sja*_*son 17

您可以通过set_error_handler结合使用来实现此目的ErrorException.

ErrorException页面的示例是:

<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
?>
Run Code Online (Sandbox Code Playgroud)

一旦您将错误作为例外处理,您可以执行以下操作:

<?php
try {
    include 'fileERROR.php5';
} catch (ErrorException $ex) {
    echo "Unable to load configuration file.";
    // you can exit or die here if you prefer - also you can log your error,
    // or any other steps you wish to take
}
?>
Run Code Online (Sandbox Code Playgroud)

  • 上面的示例直接从ErrorException docs(上面的链接)复制 - 在"官方"示例中,他们使用$ errno作为$ code,而其他人(包括在该页面上的评论中)建议将其用作$ severity - 请注意如果你愿意,可以将它用于两者,或两者兼而有之. (2认同)

小智 15

我只使用'file_exists()':

if (file_exists("must_have.php")) {
    require "must_have.php";
}
else {
    echo "Please try back in five minutes...\n";
}
Run Code Online (Sandbox Code Playgroud)

  • 最好使用[is_read()](http://www.php.net/is_read); 除了文件的可读性之外,它还检查文件是否存在(简单地说,文件必须存在才能可读)。另外,为了防止包含目录,您应该使用 [is_dir()](http://www.php.net/is_dir) (即 !is_dir($filename))。 (2认同)

mač*_*ček 5

更好的方法是首先在路径上使用realpath.如果文件不存在,realpath将返回false.

$filename = realpath(getcwd() . "/fileERROR.php5");
$filename && return require($filename);
trigger_error("Could not find file {$filename}", E_USER_ERROR);
Run Code Online (Sandbox Code Playgroud)

您甚至可以在应用程序的命名空间中创建自己的require函数,该函数包含PHP的require函数

namespace app;

function require_safe($filename) {
  $path = realpath(getcwd() . $filename);
  $path && return require($path);
  trigger_error("Could not find file {$path}", E_USER_ERROR);
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以在文件中的任何位置使用它

namespace app;

require_safe("fileERROR.php5");
Run Code Online (Sandbox Code Playgroud)


Rep*_*pox 1

我建议您查看set_error_handler()函数文档中的最新评论

它建议将以下内容作为捕获致命错误的方法(并带有示例):

<?php
function shutdown()
{
    $a=error_get_last();
    if($a==null)  
        echo "No errors";
    else
         print_r($a);

}
register_shutdown_function('shutdown');
ini_set('max_execution_time',1 );
sleep(3);
?> 
Run Code Online (Sandbox Code Playgroud)

我还没有尝试过这个建议,但这可能可以用于其他致命错误场景。