我想知道退出 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 错误页面与自定义消息一起显示。
您可以创建一个包含模板的 html 页面,然后使用 str_replace
函数替换 html 页面中的关键字。在这种情况下,我们用您的错误消息替换的单词是 {message}
.
error_page_template.html
<!DOCTYPE html>
<html>
<head>
<title>Error Page</title>
</head>
<body>
{message}
</body>
</html>
脚本.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');
?>
我链接到另一个关于脚本失败的文件,该文件采用您定义的消息并将其打印为可以随意样式的干净 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>