繁体   English   中英

从PHP文件显示404错误页面,无需重定向

[英]Show 404 error page from PHP file, without redirecting

我有一个文件secret.php ,它包含在index.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

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

暂无
暂无

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

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