【问题标题】:PHP - How can i make php to show webservers 404 error page on header 404?PHP - 如何让 php 在标头 404 上显示 webservers 404 错误页面?
【发布时间】:2015-07-22 07:27:59
【问题描述】:

我正在使用 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 文件的内容。

【问题讨论】:

  • 你可以require()header()下面的404.php文件。
  • Location 指令请求重定向到浏览器...使用 http_response_code() 设置 http 状态代码,不会重定向到该页面,而是使用 require 或 include 包含它。

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    使用file_get_contents:

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

    或者只使用回声:

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

    【讨论】:

      【解决方案3】:

      也许使用 apache .htaccess 文件是一种更好的方法。

      .htaccess:

      ErrorDocument 404 /not_found.html
      

      【讨论】:

        猜你喜欢
        • 2013-06-06
        • 2010-10-19
        • 2018-04-29
        • 2014-11-10
        • 2016-01-06
        • 2019-09-28
        • 2018-08-26
        • 2021-08-13
        • 2012-04-08
        相关资源
        最近更新 更多