Why won't my PHP app send a 404 error?

2019-01-02 17:31发布

if (strstr($_SERVER['REQUEST_URI'],'index.php')) {
    header('HTTP/1.0 404 Not Found');
}

Why wont this work? I get a blank page.

16条回答
残风、尘缘若梦
2楼-- · 2019-01-02 18:22

You're doing it right though it could use some refining. Looks like that's been addressed so let's talk practical application benefits:

An old website of ours that has a large collection of multilingual tech docs was executing this inside an if else conditional:

    if (<no file found>){
        die("NO FILE HERE");
    }

The problem (besides the unhelpful message and bad user experience) being that we generally use a link crawler (in our case integrity) to check out bad links and missing documents. This means that we were getting a perfectly correct 200 no error response telling us that there was a file there. Integrity didn't know that we were expecting a PDF so we had to manually add a 404 header with php. By adding your code above the die (because nothing afterwards would execute and header should always be before any rendered html anyway), integrity (which behaves more or less like a browser) would return a 404 and we would know exactly where to look for missing files. There are more elegant ways of telling the user that there is an error, but by serving a 404 error you are not only notifying browsers and browser-like programs of the error but (I believe-correct me if I'm wrong) are also recording those errors in your server logs where you can easily grep for 404s.

    header('HTTP/1.0 404 Not Found');
    die("NO FILE HERE");
查看更多
妖精总统
3楼-- · 2019-01-02 18:23
if($_SERVER['PHP_SELF'] == '/index.php'){ 
   header('HTTP/1.0 404 Not Found');
   echo "<h1>404 Not Found</h1>";
   echo "The page that you have requested could not be found.";
   die;
}

never simplify the echo statements, and never forget the semi colon like above, also why run a substr on the page, we can easily just run php_self

查看更多
无色无味的生活
4楼-- · 2019-01-02 18:25

Another solution, based on @Kitet's.

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

$_SERVER['REDIRECT_STATUS'] = 404;
//If you don't know which web page is in use, use any page that doesn't exists
$handle = curl_init('http://'. $_SERVER["HTTP_HOST"] .'/404missing.html');
curl_exec($handle);

If you are programming a website that hosted in a server you do not have control, you will not know which file is the "404missing.html". However you can still do this.

In this way, you provided exactly the same outcome of a normal 404 page on the same server. An observer will not be able to distinguish between an existing PHP page returns 404 and a non-existing page.

查看更多
不再属于我。
5楼-- · 2019-01-02 18:28

I came up to this problem.. I think that redirecting to a non existing link on your server might do the trick ! Because the server would return his 404:
header('Redirect abbb.404.nonexist'); < that doesnt exist for sure

查看更多
登录 后发表回答