PHP - 如何让php在标题404上显示webservers 404错误页面?

时间:2015-05-11 17:09:40

标签: php html error-handling http-status-code-404

我使用PHP编写脚本,有时我需要抛出“404 Not Found”状态消息。我试过这个:

<?php
header($_SERVER['SERVER_PROTOCOL']." 404 Not Found");
header("Location: 404.html");
exit();
?>

但它正在将用户重定向到404.html页面,我不认为这样做是好的做法。相反,我希望将用户保持在他访问的同一页面上,抛出404状态代码并显示404.html内容。

我也尝试在我的重写规则中设置错误页面,并且它正常工作。但我希望PHP能够显示404文件的内容以及404状态代码。

我也尝试过:

<?php
header($_SERVER['SERVER_PROTOCOL']." 404 Not Found");
exit(); 

但这仅提供404状态代码和空白页面。我想获取404.html或404.php文件的内容。

3 个答案:

答案 0 :(得分:1)

使用include包含其中包含404错误消息的文件,并将标头设置为404。 请确保在输出任何其他内容之前发送标题。

<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
include("404.html");
exit(); // terminate the script
?>

答案 1 :(得分:0)

使用file_get_contents

header($_SERVER['SERVER_PROTOCOL'].file_get_content("404.html"));
exit(); 

或者只使用echo:

echo file_get_content("404.html");
exit();

答案 2 :(得分:0)

使用apache .htaccess文件可能是更好的方法。

.htaccess

ErrorDocument 404 /not_found.html