简体   繁体   English

PHP-如何制作PHP以在标题404上显示Web服务器404错误页面?

[英]PHP - How can i make php to show webservers 404 error page on header 404?

I am using PHP for scripting, and sometimes I need to throw a "404 Not Found" status message. 我使用PHP编写脚本,有时需要抛出“ 404 Not Found”状态消息。 I have tried this: 我已经试过了:

<?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. 但这会将用户重定向到404.html页面,我认为这样做不是一个好习惯。 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状态代码并显示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. 但这仅给出404状态代码和空白页。 I would like to get the contents of a 404.html or 404.php file. 我想获取404.html或404.php文件的内容。

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错误消息的文件include在内,并将标头设置为404。请确保在输出其他任何内容之前发送标头。

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

Use file_get_contents : 使用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();

Maybe It's a better way do it with apache .htaccess file. 也许这是使用apache .htaccess文件的更好方法。

In .htaccess : .htaccess

ErrorDocument 404 /not_found.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM