Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Mar 2009
    Posts
    21
    Thanks
    3
    Thanked 2 Times in 2 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
    New Coder
    Join Date
    Mar 2009
    Posts
    21
    Thanks
    3
    Thanked 2 Times in 2 Posts
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •