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

Viewed 779

I am wondering what is the best way I can exit a php script (if I encounter an error) where I also include all my html code too. Currenty my script is:

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

You can see my exit message has bad style (since I am cramming all my html there). Is there a way where I can have a nice html error page to show with the custom message.

2 Answers

You can make a html page that has the template and then use the str_replace function to replace a keyword in the html page. In this case the word we are replacing with your error message is {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');
?>

Here I am linking to another file on script failure that takes your defined message and prints it as clean HTML5 that can be styles at will.

I think this is your best option (script utilizes a file that you must include on error):

<?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");
?>

Then there is the other file (that is being linked to):

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