Web Analytics Made Easy -
StatCounter Custom 404 page and proper status code together? How? - CodingForum

Announcement

Collapse
No announcement yet.

Custom 404 page and proper status code together? How?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Custom 404 page and proper status code together? How?

    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:

    Code:
    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:

    Code:
    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.

  • #2
    Never mind I solved it:

    Code:
    function NotFound()
    {
    	ob_start();
    	include('/path/to/your/custom/error/page/404.php');
    	$contents = ob_get_contents();
    	ob_end_clean();
    	Header('HTTP/1.1 404 Not Found');
    	Header('Cache-Control: no-store, no-cache');
    	Header('Content-Length: '.strlen($contents));
    	echo $contents;
    	exit();
    }
    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.

    Comment

    Working...
    X