Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display Apache's default 404 page in PHP

I have a webapp that needs to process the URI to find if a page exists in a database. I have no problem directing the URI to the app with .htaccess:

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*)$ index.php?p=$1 [NC]

My problem is that if the page does not exist, I do not want to use a custom 404 handler written in PHP, I would like do show the default Apache 404 page. Is there any way to get PHP to hand execution back to Apache when it has determined that the page does not exist?

like image 551
Matt Avatar asked May 10 '11 16:05

Matt


People also ask

Can a 404 page be PHP?

php file, you can create one as a simple HTML file with a . php extension and then upload it to your site's theme directory. Any time a 404 error occurs, WordPress will serve up this 404. php page to the user.

Does WordPress have a default 404 page?

Every theme that is shipped with WordPress has a 404. php file, but not all Themes have their own custom 404 error template file.


1 Answers

I don't think you can "hand it back" to Apache, but you can send the appropriate HTTP header and then explicitly include your 404 file like this:

if (! $exists) {
    header("HTTP/1.0 404 Not Found");
    include_once("404.php");
    exit;
}

Update

PHP 5.4 introduced the http_response_code function which makes this a little easier to remember.

if (! $exists) {
    http_response_code(404);
    include_once("404.php");
    exit;
}
like image 144
andrewtweber Avatar answered Oct 04 '22 04:10

andrewtweber