如何在出现自定义 html 消息错误时退出 php

How can I exit php upon error with a custom html message

我想知道退出 php 脚本(如果我遇到错误)的最佳方式是什么,我还包含了我所有的 html 代码。目前我的脚本是:

<?php

    // Some other code here

    // These if statements are my error handling
    if(!isset($var)) {
        $message = 'Var is not set'
        exit('<title>Error Page</title>'.$message.'<footer>Test Footer</foot>');
    }

    if($a != $b) {
        $message = 'a is not equal to b';
        exit('<title>Error Page</title>'.$message.'<footer>Test Footer</foot>');
    }

    $success = 'YAY, we made it to the end';
?>

<html>
    <header>
        <title>YAY</title>
        <!-- Other stuff here -->
    </header>
    <!-- Other stuff here -->
    <body>
    <!-- Other stuff here -->
    <?php echo $success ?>
    <!-- Other stuff here -->
    </body>
    <!-- Other stuff here -->
    <footer>The best footer</footer>
</html>

您可以看到我的退出消息风格不佳(因为我在那里塞满了所有 html)。有没有一种方法可以让我有一个漂亮的 html 错误页面来显示自定义消息。

我在这里链接到另一个关于脚本失败的文件,它接受你定义的消息并将其打印为干净的HTML5,可以随意设置样式。

我认为这是你最好的选择(脚本使用了一个你必须包含错误的文件):

<?php
//On failure (this is the error)
$message = 'Error message';
//I can use a variable inside double quotes because they do not take the string
//literally, if it were single quotes it would take the string as a literal and it
//would print $message as $message
//The `die()` function kills the script and executes whatever you put inside of it.

die(require "e_include.php");
?>

然后是另一个文件(被链接到):

<!DOCTYPE html>
<html>
<head>
    <title>YAY</title>
    <meta charset="utf-8">
</head>
<body>
    <p><?php echo $message ?></p>
</body>
</html>

您可以制作一个包含模板的html页面,然后使用str_replace功能替换html页面中的关键字。在这种情况下,我们用您的错误消息替换的词是 {message}.

error_page_template.html

<!DOCTYPE html>
<html>
    <head>
        <title>Error Page</title>
    </head>
    <body>

        {message}

    </body>
</html>

script.php

<?php

    function error_page($message) {
        $htmlTemplate = file_get_contents('error_page_template.html');
        $errorPage = str_replace('{message}', $message, $htmlTemplate);
        return $errorPage;
    }

    echo error_page('An error has occurred');
?>