PHP - Display a 404 Error without redirecting to another page

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;