如何在出现错误时使用自定义html消息退出php
我想知道退出php脚本(如果我遇到错误)的最佳方式是什么,在该脚本中我还包括所有html代码。当前我的脚本是:如何在出现错误时使用自定义html消息退出php,php,html,exit,die,Php,Html,Exit,Die,我想知道退出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
<?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,可以随意使用样式 我认为这是您最好的选择(脚本使用了一个您必须在出错时包含的文件):
然后是另一个文件(正在链接到):
耶
您可以创建一个包含模板的html页面,然后使用str\u replace
功能替换html页面中的关键字。在这种情况下,我们用错误消息替换的单词是{message}
错误页面\u template.html
<!DOCTYPE html>
<html>
<head>
<title>Error Page</title>
</head>
<body>
{message}
</body>
</html>
错误页
{message}
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');
?>
但为什么要退出脚本?正如我所看到的,您可以在HTML上下文中运行它,因此您几乎不应该使用exit@Dharman这是一个示例脚本,但是退出的目的是因为我们遇到了一个错误,所以我想退出并显示一条漂亮的html格式的错误消息。您对处理错误有何建议?是否仍要打印底部的html部分?如果没有,那么您可以回显“您的html代码”;退出()
在if
@catcon中,它们是示例if语句。在我的实际代码(更长)中,它有不同的if语句(正确处理错误)。我不想发布长代码,因为这不是我要问的问题谢谢!我没有想到这一点,但这是我基本上想要的。
<!DOCTYPE html>
<html>
<head>
<title>Error Page</title>
</head>
<body>
{message}
</body>
</html>
<?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');
?>