Reputation:
I am using PHP for scripting, and sometimes I need to throw a "404 Not Found" status message. I have tried this:
<?php
header($_SERVER['SERVER_PROTOCOL']." 404 Not Found");
header("Location: 404.html");
exit();
?>
But it's redirecting the user to the 404.html
page and I don't think it's good practice to do so. Instead, I would like to keep the user on the same page which he accessed, throw a 404 status code and show the 404.html contents.
I have also tried setting the error page in my rewrite rules, and it's working correctly. But I want PHP to show the 404 file's content along with a 404 status code.
I have also tried doing:
<?php
header($_SERVER['SERVER_PROTOCOL']." 404 Not Found");
exit();
But this gives only a 404 status code and a blank page. I would like to get the contents of a 404.html or 404.php file.
Upvotes: 1
Views: 1582
Reputation: 2863
Use include
to include the file with the 404 error message in it and set the header to 404.
Please make sure you send the header before outputting anything else.
<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
include("404.html");
exit(); // terminate the script
?>
Upvotes: 1
Reputation:
Maybe It's a better way do it with apache .htaccess
file.
In .htaccess
:
ErrorDocument 404 /not_found.html
Upvotes: 0
Reputation: 833
Use file_get_contents
:
header($_SERVER['SERVER_PROTOCOL'].file_get_content("404.html"));
exit();
Or just use echo:
echo file_get_content("404.html");
exit();
Upvotes: 0