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


Show 404 error page from PHP file, without redirecting

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

header("Location: this_site_certainly_does_not_exist");

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

您可以使用头执行此操作。

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();

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

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

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

我不确定您的应用程序体系结构,但Codeignter通过包含一个在所有文件中使用的公共文件(在其情况下为index.php)来实现这一点

index.php文件包括一个定义

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

然后在文件中,应该只被包括在其他文件中使用

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

看看你如何根据自己的情况采用这个方案。

对于永久解决方案,当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