How can I create an error 404?
My .htaccess redirects all requests 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?
Verified Answer (142 Votes) ✓
The up-to-date answer (as of PHP 5.4 or newer) for generating 404 pages is to use
<?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.
Answer #2 (87 Votes)
What you're doing will work, and the browser will receive a 404 code. What it won't do is display the "not found" page that you might be expecting, e.g.:
The requested URL /test.php was not found on this server.
That's because the web server doesn't send that page when PHP returns a 404 code (at least Apache doesn't). PHP is responsible for sending all its own output. So if you want a similar page, you'll have to send the HTML yourself, e.g.:
<?php header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404); include("notFound.php"); ?>
You could configure Apache to use the same page for its own 404 messages, by putting this in httpd.conf:
ErrorDocument 404 /notFound.php
Answer #3 (22 Votes)
<?php header("HTTP/1.0 404 Not Found"); ?>