PHP or htaccess make dynamic url page to go 404 when item is missing in DB

余生颓废 提交于 2019-12-06 07:25:35

Hmm. Two ideas come to mind:

  • Redirect to the 404 page using header("Location:...") - this is not standards-compliant behaviour though. I would use that only as a last straw

  • Fetch and output the Apache-parsed SHTML file using file_get_contents("http://mydomain.com/404.shtml"); - also not really optimal because a request is made to the web server but, I think, acceptable in most cases.

I doubt there is anything you can do in .htaccess because the PHP script runs after any rewrite rules have already been parsed.

IF you are using apache mod_php, use virtual('/404.shtml'); to display the parsed shtml page to your user.

I was trying to do this exact same thing yesterday.

Does Pekka's file_get_contents/include result in a 404 status header being sent? Perhaps you need to do this before including the custom error page?

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");

You can test using this Firefox extension.

I was looking exactly for something like you needed, so you have a page:

http://example.com/page?item_id=456

and if later you want that if item is missing you are redirected to:

http://example.com/page_not_found?item_id=456

In reality I found it is much more maintainable solution to just use the original page as 404 page.

<?php
    $item = findItem( $_GET['item_id']);
    if($item === false){
        //show 404 page sending correct header and then include 404 message
        header( $_ENV['SERVER_PROTOCOL'].' 404 Not Found', true );
        // you can still use $_GET['item_id'] to customize error message
        // "maybe you were looking for XXX item"
        include('somepath/missingpage.php');
        return;
    }

    //continue as usual with normal page

?>

So if item is no longer in the DB, the 404 page is showed but you can provide custom items in replace or error messages.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!