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

If you want the server’s default error page to be displayed, you have to handle this in the server.

查看更多
春风洒进眼中
3楼-- · 2019-01-02 18:08

Your code is technically correct. If you looked at the headers of that blank page, you'd see a 404 header, and other computers/programs would be able to correctly identify the response as file not found.

Of course, your users are still SOL. Normally, 404s are handled by the web server.

  • User: Hey, do you have anything for me at this URI webserver?
  • Webserver: No, I don't, 404! Here's a page to display for 404s.

The problem is, once the web server starts processing the PHP page, it's already passed the point where it would handle a 404

  • User: Hey, do you have anything for me at this URI webserver?
  • Webserver: Yes, I do, it's a PHP page. It'll tell you what the response code is
  • PHP: Hey, OMG 404!!!!!!!
  • Webserver: Well crap, the 404 page people have already gone home, so I'll just send along whatever PHP gave me

In addition to providing a 404 header, PHP is now responsible for outputting the actual 404 page.

查看更多
倾城一夜雪
4楼-- · 2019-01-02 18:08

Since php 5.4 you can now do http_response_code(404);

查看更多
一个人的天荒地老
5楼-- · 2019-01-02 18:11

try with:

header("Status: 404 Not Found");
header('HTTP/1.0 404 Not Found');

Bye!

查看更多
像晚风撩人
6楼-- · 2019-01-02 18:12
if (strstr($_SERVER['REQUEST_URI'],'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.";
    exit();
}

If you look at the last two echo lines, that's where you'll see the content. You can customize it however you want.

查看更多
只若初见
7楼-- · 2019-01-02 18:14

That is correct behaviour, it's up to you to create the contents for the 404 page.
The 404 header is used by spiders and download-managers to determine if the file exists.
(A page with a 404 header won't be indexed by google or other search-engines)

Normal users however don't look at http-headers and use the page as a normal page.

查看更多
登录 后发表回答