phphttp-status-code-404server-response

How to detect PHP script is being used as ErrorDocument for 404 Not Found?


Let's say I have a test.php file, configured to handle Apache 404 errors with ErrorDocument 404 /test.php

What PHP code do I have to add to check if we're really handling a 404, and test.php has not been called directly?

Like:

<?php
if (server_response_code == 404) {
    echo "It's a 404!"
}
?>

P.S. There's no 404 forwarding or so…


Solution

  • One way to do this would be simply look at the $_SERVER['REQUEST_URI'] and determine if it points at something invalid.

    While your example is probably simplified for this question, it might be as simple as

    if ($_SERVER['REQUEST_URI'] != 'test.php') {
        //we are handling a 404
        header("HTTP/1.0 404 Not Found");
        echo "These aren't the droids you're looking for";
    }
    

    You may need more complex logic, but will all boil down to looking at the request and detecting it was invalid.

    As long as the ErrorDocument is a relative URL (doesn't start with http://...), then you should find your script has some extra $_SERVER variables, e.g.

    $_SERVER["REDIRECT_URL"]; // /original/path
    $_SERVER['REDIRECT_STATUS']; // 404
    

    See the ErrorDocument documentation for more details.

    Alternatively, just pass a query string arg to the 404 handler, e.g. ErrorDocument 404 /test.php?error=404 :)