Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 506
Marcus McLean Avatar asked May 27 '26 08:05

Marcus McLean


1 Answers

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
like image 125
Boaz Avatar answered Jun 01 '26 12:06

Boaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!