显示PHP文件中的404错误页面,不重定向

显示PHP文件中的404错误页面,不重定向,php,http-status-code-404,Php,Http Status Code 404,我有一个文件secret.php,它包含在index.php中,当有人试图直接访问secret.php时,我想显示一个404错误页面。但是 header("Location: this_site_certainly_does_not_exist"); 在secure.php中不是一个解决方案,因为我希望用户键入的URL(例如example.com/secret.php)在显示错误页面时在浏览器的URL栏中可见,而不是重定向。我不明白为什么要将其保留在浏览器中,最佳做法是将用户重定向到404页面

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

header("Location: this_site_certainly_does_not_exist");

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

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


我建议使用apache(.htaccess)或nginx重定向执行此操作。

您可以使用头执行此操作

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();
标题(“未找到HTTP/1.0 404”);
回显“404未找到”;
echo“找不到您请求的页面。”;
退出();

您需要向客户端发送html 404状态代码。您可以通过以下方式实现这一目标:

对于永久解决方案,您可以在调用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

我不确定您的应用程序架构,但Codeigner通过包含一个在所有文件中使用的公共文件(在其案例index.php中)来实现这一点

php文件包含一个define

define('BASEPATH', $system_folder.'/');
然后在只应包含在其他文件中的文件中使用

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

它只向客户端发送404状态代码,不显示默认的404错误页面。如果您有不同的404页面模板,只需
文件\u获取\u内容
包含它。从何处包含它?检查此答案以获得可能的解决方案