PHP - Display a 404 Error without redirecting to another page

房东的猫 提交于 2019-11-28 06:32:52
Emil Vikström

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.
}
?>

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).

You can achieve a 404 (or any other HTTP response code really) programmatically with

header('HTTP/1.0 404 Not Found');
die;

In my experience the best way to show 404 error document without changing URL is to define error document in apaches .htaccess file:

RewriteEngine on
RewriteBase /

# Defines 404 error pages content:
ErrorDocument 404 /my_root/errors/404.html

# for all invalid links (non existing files):
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* - [L,R=404]

# for some valid links (existing files to be un-accessible):
RewriteCond %{THE_REQUEST} ^.*some_file.php.*$ [NC]
RewriteRule .* - [L,R=404]

What you write makes it hard to us to understand.

I want to redirect any incoming user to the 404 Error Page if s/he reaches the page I don't want him/her to reach.

So, a person reaches a page that exists?

If the person reaches for example a protected page that he/she is not supposted to see. Using header is the best way. Your options are to echo meta-refresh or javascript, but header is much cleaner. You could display something like You do not have permission to do that! which is pretty common on the web. If you don't want to redirect you could display a 404 "fake message" via the header.

If you are talking about someone reaching a 404 page, a file that does not exists, you only option is to use .htaccess

may you can direct to your 404 page like

header('Location: http://www.website.com/errors/404.php');

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!