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.
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
Try this:
<?php
header("HTTP/1.0 404 Not Found");
?>
Create custom error pages through .htaccess file
1. 404 - page not found
RewriteEngine On
ErrorDocument 404 /404.html
2. 500 - Internal Server Error
RewriteEngine On
ErrorDocument 500 /500.html
3. 403 - Forbidden
RewriteEngine On
ErrorDocument 403 /403.html
4. 400 - Bad request
RewriteEngine On
ErrorDocument 400 /400.html
5. 401 - Authorization Required
RewriteEngine On
ErrorDocument 401 /401.html
You can also redirect all error to single page. like
RewriteEngine On
ErrorDocument 404 /404.html
ErrorDocument 500 /404.html
ErrorDocument 403 /404.html
ErrorDocument 400 /404.html
ErrorDocument 401 /401.html
Did you remember to die() after sending the header? The 404 header doesn't automatically stop processing, so it may appear not to have done anything if there is further processing happening.
It's not good to REDIRECT to your 404 page, but you can INCLUDE the content from it with no problem. That way, you have a page that properly sends a 404 status from the correct URL, but it also has your "what are you looking for?" page for the human reader.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With