Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Display a 404 Error without redirecting to another page

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

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

like image 704
Dilip Raj Baral Avatar asked Jun 21 '12 11:06

Dilip Raj Baral


1 Answers

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

like image 86
Emil Vikström Avatar answered Sep 20 '22 16:09

Emil Vikström