How can I create an error 404 in PHP?

Eric picture Eric · Sep 4, 2009 · Viewed 193.3k times · Source

My .htaccess redirects all requests to /word_here to /page.php?name=word_here. The PHP script then checks if the requested page is in its array of pages.

If not, how can I simulate an error 404? I tried this, but it didn't result in my 404 page configured via ErrorDocument in the .htaccess showing up.

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");

Am I right in thinking that it's wrong to redirect to my error 404 page?

Answer

blade picture blade · Jan 11, 2017

The up-to-date answer (as of PHP 5.4 or newer) for generating 404 pages is to use http_response_code:

<?php
http_response_code(404);
include('my_404.php'); // provide your own HTML for the error page
die();

die() is not strictly necessary, but it makes sure that you don't continue the normal execution.