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

aoyhnmkz  于 2023-02-07  发布在  PHP
关注(0)|答案(7)|浏览(207)

我正在写一个脚本在PHP5中,需要某些文件的代码。当一个文件是不可用的包含,第一个警告,然后一个致命的错误抛出。我想打印自己的错误消息,当它是不可能包括代码。是否有可能执行最后一个命令,如果requeire不工作?

require('fileERROR.php5') or die("Unable to load configuration file.");

使用error_reporting(0)抑制所有错误消息只会出现白色,而不使用error_reporting会出现PHP错误,我不想显示这些错误。

cxfofazt

cxfofazt1#

您可以通过将set_error_handlerErrorException结合使用来实现此目的。
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();
?>

将错误作为异常处理后,您可以执行以下操作:

<?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
}
?>
wfsdck30

wfsdck302#

我只使用'file_exists()':

if (file_exists("must_have.php")) {
    require "must_have.php";
}
else {
    echo "Please try back in five minutes...\n";
}
njthzxwz

njthzxwz3#

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

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

您甚至可以在应用的namespace中创建自己的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);
}

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

namespace app;

require_safe("fileERROR.php5");
n6lpvg4x

n6lpvg4x4#

你需要使用include()。当Require()用于不存在的文件时,会产生致命错误并退出脚本,所以你的die()不会发生。Include()只抛出警告,然后脚本继续。

ghhkc1vu

ghhkc1vu5#

我建议您查看文档中关于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);
?>

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

xriantvc

xriantvc6#

我使用的一个简单方法是

<?php
    ...
    if(!include 'config.php'){
        die("File not found handler. >_<");
    }
   ...
?>
oxf4rvwz

oxf4rvwz7#

从PHP 7.0开始,您可以捕获require()抛出的Throwable异常。

try {
    require '/path/not-found/or-not-available.php';
}
catch (Error $e) {
    // debugging example:
    die('Caught error => ' . $e->getMessage());
}

将输出如下内容:
捕获错误=〉无法打开所需的“/path/not-found/or-not-available.php”[...]

相关问题