mauriblint
mauriblint

Reputation: 1707

Throw 404 Not Found from PHP

How can I throw from php an error code 404? In my htaccess I have a rule that redirect tags to categories, but if after search the category in the DB, if is not exist, how can I redirect to 404 error page and send the correct headers?

RewriteRule ^([a-z]{2})/(.*)$ index.php?lang=$1&id=$2 [L]

How can I handle this url?

site.com/en/this-category-not-exists

Upvotes: 1

Views: 7470

Answers (2)

Stubborn
Stubborn

Reputation: 968

If the record does not exist, you can use this code:

<?php
header("HTTP/1.0 404 Not Found");
echo 'This page was not found';
?>

If you want to use an external 404 error page, you can use this instead:

<?php
header("HTTP/1.0 404 Not Found");
include("404errorpage.php");
?>

Alternatively, you can redirect to the 404 error page using

header("Location: http://example.com/404errorpage.php");

But then you'll have to put

header("HTTP/1.0 404 Not Found");

Into the 404 error page

Upvotes: 2

anubhava
anubhava

Reputation: 784888

Starting from PHP >= 5.4.0 you can use http_response_code function for this:

if ($notExistDB) {
   http_response_code(404);
   exit;
}

Upvotes: 3

Related Questions