How to display Apache's default 404 page in PHP

余生长醉 提交于 2019-12-03 23:31:30

The only possible way I am aware of for the above scenario is to have this type of php code in your index.php:

<?php
if (pageNotInDatabase) {
   header('Location: ' . $_SERVER["REQUEST_URI"] . '?notFound=1');
   exit;
}

And then slightly modify your .htaccess like this:

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

That way Apache will show default 404 page for this special case because of extra query parameter ?notFound=1 added from php code and with the negative check for the same in .htaccess page it will not be forwarded to index.php next time.

PS: A URI like /foo, if not found in database will become /foo?notFound=1 in the browser.

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;
}
AJ.

Call this function:

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