View Full Version : Custom 404 page and proper status code together? How?

04-05-2009, 06:43 PM
Hi all,

Another small issue I am having is as follows.

I have a custom 404.php page which shows site navigation and a google search box set to search the site by default.

In some of my php files I have a need to return 404 status to the client (for example wrong category, or filename, etc).

But if I do:

Header("HTTP/1.1 404 File Not Found");

The client gets a blank page instead of my custom 404.php page.

If on the other hand I do this:

Header("Location: /404.php");

Then the browser (and the googlebot as well) first get 302 response code, than 200 OK code which are both wrong.

In other words, I can either return 404 status code, but my custom 404 page doesn't show or I can show the page but send the wrong status code.

I am pulling my hair over this one so I would appreciate any help.

04-05-2009, 07:45 PM
Never mind I solved it:

function NotFound()
$contents = ob_get_contents();
Header('HTTP/1.1 404 Not Found');
Header('Cache-Control: no-store, no-cache');
Header('Content-Length: '.strlen($contents));
echo $contents;

Now just call NotFound() wherever you need provided that the output hasn't already started which shouldn't be a problem because it is always better to do all the checking before starting the output.