我想知道退出php脚本(如果遇到错误)的最佳方法是什么,我也将所有html代码也包括在内。当前我的脚本是:
1
您可以看到我的退出消息的样式不好(因为我在那儿塞满了所有的html)。有没有一种方法可以使我在自定义消息中显示漂亮的html错误页面。
答案 0 :(得分:4)
您可以制作一个具有模板的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');
?>
答案 1 :(得分:0)
这里,我在脚本失败时链接到另一个文件,该文件将接收您定义的消息并将其打印为可以随意设置样式的干净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>