简体   繁体   中英

http_response_code() always returns 200, even on 404

I'm trying to use Apache's ErrorDocument to handle client and server errors by passing them to error.php .

.htaccess

ErrorDocument 400 /error.php
...
ErrorDocument 404 /error.php
...
ErrorDocument 511 /error.php

error.php

var_dump(http_response_code());

So, I point my browser to mywebsite.com/noeutdhoaeu , which does not exist. The response from the server is 404 Not Found , as you would expect. But PHP gives me 200 .

What gives?

Edit : I have this same exact code on my Apache-based localhost and it works just fine. That is the reason I am asking this question. PHP is completely aware that a 404 error has occurred in my local environment. On my hosted environment, however, PHP has no idea.

This function is basically a setter/getter for PHP 's response code. Without parameters, this function returns the currently set response code by PHP . Since the default response code is 200 , without setting a different code by first passing a parameter, 200 will always be returned.

See this example in the manual :

var_dump(http_response_code()); // int(200) - default
http_response_code(404); // set a new code
var_dump(http_response_code()); // int(404) - new code

It's also worth noting that header() calls may also affect the return value of this function, for example:

header('http/1.0 404 not found');
var_dump(http_response_code()); // int(404) - new code

As @Boaz said, PHP doesn't know what Apache is going to set later.

You could use this approach to use the error code in PHP:

ErrorDocument 400 /error.php?error=400
ErrorDocument 401 /error.php?error=401
...

And in PHP test $_GET["error"] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM