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.
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');
?>