I am using PHP for scripting, and sometimes I need to throw a "404 Not Found" status message. I have tried this:
我使用PHP进行脚本编写,有时我需要抛出“404 Not Found”状态消息。我试过这个:
<?php
header($_SERVER['SERVER_PROTOCOL']." 404 Not Found");
header("Location: 404.html");
exit();
?>
But it's redirecting the user to the 404.html
page and I don't think it's good practice to do so. Instead, I would like to keep the user on the same page which he accessed, throw a 404 status code and show the 404.html contents.
但它正在将用户重定向到404.html页面,我认为这样做不是好习惯。相反,我想让用户保持他访问的同一页面,抛出404状态代码并显示404.html内容。
I have also tried setting the error page in my rewrite rules, and it's working correctly. But I want PHP to show the 404 file's content along with a 404 status code.
我也尝试在我的重写规则中设置错误页面,并且它正常工作。但我希望PHP显示404文件的内容以及404状态代码。
I have also tried doing:
我也尝试过:
<?php
header($_SERVER['SERVER_PROTOCOL']." 404 Not Found");
exit();
But this gives only a 404 status code and a blank page. I would like to get the contents of a 404.html or 404.php file.
但这只提供404状态代码和空白页面。我想获取404.html或404.php文件的内容。
3 个解决方案
#1
Use include
to include the file with the 404 error message in it and set the header to 404. Please make sure you send the header before outputting anything else.
使用include包含文件中包含404错误消息并将标题设置为404.请确保在输出任何其他内容之前发送标题。
<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
include("404.html");
exit(); // terminate the script
?>
#2
Use file_get_contents
:
header($_SERVER['SERVER_PROTOCOL'].file_get_content("404.html"));
exit();
Or just use echo:
或者只使用echo:
echo file_get_content("404.html");
exit();
#3
Maybe It's a better way do it with apache .htaccess
file.
也许这是用apache .htaccess文件做的更好的方法。
In .htaccess
:
ErrorDocument 404 /not_found.html
#1
Use include
to include the file with the 404 error message in it and set the header to 404. Please make sure you send the header before outputting anything else.
使用include包含文件中包含404错误消息并将标题设置为404.请确保在输出任何其他内容之前发送标题。
<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
include("404.html");
exit(); // terminate the script
?>
#2
Use file_get_contents
:
header($_SERVER['SERVER_PROTOCOL'].file_get_content("404.html"));
exit();
Or just use echo:
或者只使用echo:
echo file_get_content("404.html");
exit();
#3
Maybe It's a better way do it with apache .htaccess
file.
也许这是用apache .htaccess文件做的更好的方法。
In .htaccess
:
ErrorDocument 404 /not_found.html