有没有办法从php中包含文件跳过致命错误?

Sar*_*CSE 7 php fatal-error

如果我在php中包含一个文件.如果该php中有任何致命错误,那么有没有办法跳过它.

<?php
   include "somefile.php";
   echo "OK"; // Is there any way to print this OK  If there is any fatal error on somefile.php
?>
Run Code Online (Sandbox Code Playgroud)

我需要包含这个somefile.php文件.它可能会返回某些主机的致命错误.我想跳过这个主机的文件.

请告诉我.

jlg*_*all 5

有了这个,您可以定义自己的延续函数,该函数将在发生致命错误时接管。这用于register_shutdown_function()拦截致命错误。

用法:

function my_continuation_func($filename, $arg2) {
    // On fatal error during include, continue script execution from here.
    // When this function ends, or if another fatal error occurs,
    // the execution will stop.
}

include_try('my_continuation_func', array($filename, $arg2));
$data = include($filename);
$error = include_catch();
Run Code Online (Sandbox Code Playgroud)

如果发生致命错误(如解析错误),脚本将从my_continuation_func(). 否则,如果解析期间出现错误,则include_catch()返回。true

的任何输出(如echo 'something';)都include()被视为错误。true除非您通过将第三个参数传递给 来启用输出include_try()

此代码会自动处理关闭功能中可能的工作目录更改。

您可以将其用于任意数量的包含,但无法拦截发生的第二个致命错误:执行将停止。

需包含的功能:

function include_try($cont_func, $cont_param_arr, $output = false) {
    // Setup shutdown function:
    static $run = 0;
    if($run++ === 0) register_shutdown_function('include_shutdown_handler');

    // If output is not allowed, capture it:
    if(!$output) ob_start();
    // Reset error_get_last():
    @user_error('error_get_last mark');
    // Enable shutdown handler and store parameters:
    $params = array($cont_func, $cont_param_arr, $output, getcwd())
    $GLOBALS['_include_shutdown_handler'] = $params;
}

function include_catch() {
    $error_get_last = error_get_last();
    $output = $GLOBALS['_include_shutdown_handler'][2];
    // Disable shutdown handler:
    $GLOBALS['_include_shutdown_handler'] = NULL;
    // Check unauthorized outputs or if an error occured:
    return ($output ? false : ob_get_clean() !== '')
        || $error_get_last['message'] !== 'error_get_last mark';
}

function include_shutdown_handler() {
    $func = $GLOBALS['_include_shutdown_handler'];
    if($func !== NULL) {
        // Cleanup:
        include_catch();
        // Fix potentially wrong working directory:
        chdir($func[3]);
        // Call continuation function:
        call_user_func_array($func[0], $func[1]);
    }
}
Run Code Online (Sandbox Code Playgroud)