【问题标题】:Show 404 error page from PHP file, without redirecting显示 PHP 文件中的 404 错误页面,无需重定向
【发布时间】:2016-01-04 04:20:29
【问题描述】:

我有一个文件secret.php,它包含在index.php 中,当有人尝试直接访问secret.php 时,我想显示一个404 错误页面。但是

header("Location: this_site_certainly_does_not_exist");

secure.php 不是解决方案,因为我希望用户键入的 URL(例如 example.com/secret.php)在显示错误页面时在浏览器的 URL 栏中可见,而不是重定向。

【问题讨论】:

标签: php http-status-code-404


【解决方案1】:

你可以用标题做到这一点。

header("HTTP/1.0 404 Not Found");

然后您可以使用例如readfile 方法添加您的 404 页面。

header("HTTP/1.0 404 Not Found");
echo "<h1>404 Not Found</h1>";
echo "The page that you have requested could not be found.";
exit();

【讨论】:

  • 如果您有不同的 404 页面模板,只需 file_get_contentsinclude 即可。
  • 从哪里包含它?
【解决方案2】:

您需要向客户端发送一个 html 404 状态码。您可以通过以下方式实现: http://www.php.net/manual/en/function.http-response-code.php

【讨论】:

  • 它只向客户端发送 404 状态码,不显示默认的 404 错误页面。
【解决方案3】:

我不明白您为什么要将其保留在浏览器中,最佳做法是将用户重定向到 404 页面。

我建议使用 apache (.htaccess) 或 nginx 重定向。

【讨论】:

    【解决方案4】:

    我不确定您的应用程序架构,但 Codeignter 通过包含一个在所有文件(在他们的情况下为 index.php)中使用的通用文件来做到这一点

    index.php 文件包含一个定义

    define('BASEPATH', $system_folder.'/');
    

    然后在应该只被包含在其他文件中使用的文件中

    <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    

    了解如何根据自己的情况采用该方案。

    【讨论】:

      【解决方案5】:

      对于永久解决方案,您可以在调用 secret.php 时使用 .htaccess 进行重定向

        # Mod for redirecting specific URL requests to a custom error page
        RewriteEngine On
        RewriteBase /
        RewriteCond %{REQUEST_FILENAME} ^/secret.php [NC]
        RewriteRule . /your-error-page.php [L]
        # End of custom mod
      

      【讨论】:

        猜你喜欢
        • 2013-06-09
        • 1970-01-01
        • 2011-11-17
        • 1970-01-01
        • 1970-01-01
        • 2016-01-06
        • 2013-06-06
        • 2023-03-27
        • 2018-10-14
        相关资源
        最近更新 更多