PHP-显示404错误而不重定向到另一个页面 [英] PHP - Display a 404 Error without redirecting to another page

查看:211
本文介绍了PHP-显示404错误而不重定向到另一个页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户访问的页面存在但我不希望他/她看到,我想显示404错误.

I want to display a 404 Error if a user reaches a page that exists but I don't want him/her to see.

我不想执行重定向(这将导致地址栏在地址栏中显示错误页面的链接),如下所示:

I don't want to do redirect (that would cause the address bar to show the link of the error page in the address bar) like the following:

if ($this_page_should_not_be_seen)
   header("Location: err.php?e=404");

相反,在没有更改浏览器地址中URL的情况下,该页面似乎确实不存在.

Instead, it should seem like the page really doesn't exist, without having the URL in the browser's address changed.

推荐答案

在当前页面中包含错误页面并发送404错误状态代码:

Include the error page in your current page and send a 404 error status code:

<?php
if ($nobody_should_ever_be_here) {
  header('HTTP/1.1 404 Not Found'); //This may be put inside err.php instead
  $_GET['e'] = 404; //Set the variable for the error code (you cannot have a
                    // querystring in an include directive).
  include 'err.php';
  exit; //Do not do any more work in this script.
}
?>

请注意,如果从不显示页面,则应使用此选项.对于未经授权的访问(如果某些登录的用户应该可以看到该页面),更好的状态代码是403(未经授权).

Note that this should be used if the page should never be seen. A better status code for un-authorized access (if the page should be seen by some logged in users) is 403 (Not Authorized).

这篇关于PHP-显示404错误而不重定向到另一个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆