PHP navigate to error page

2019-09-05 14:14发布

问题:

In my website, website.com/downloads actually goes to website.com/index.php?page=downloads (with apache rewriting). I have a custom 404 not found error page set. If I do website.com/dkfjf/fdf, It goes to the 404 error, but If I do website.com/something, it goes to index.php?page=something, so then in my index.php, how can I make it just navigate to 404 error, after I determine there is no something page? Because right now, I just load the my 404 error page into the main div (like all other pages), but it's inconsistent (e.g., it still displays website.com/soemthing in address bar, and there's other problems), and I just want to make it navigate to 404 error. How can I do that?

EDIT: this worked:

echo '<meta http-equiv="refresh" content="0; url = /error" />';

(mywebsite.com/error rewrites to index.php?page=error, which is my 404 error page). Is that a bad approach?

回答1:

Use the header function to send the correct status code:

header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404);

Then you can send your error document with readfile if it’s a static file or with include if it’s a PHP file.