echo http_response_code('400');
return "error";
I have a page required to output http
status
I set http_response_code(400)
& try to use postman to post.
It always return 200.
why http_response_code
is not working?
The http_response_code() function sets or returns the HTTP response status code.
For PHP versions 4.0: In order to send the HTTP response code, we need to assemble the response code. To achieve this, use header() function. The header() function contains a special use-case which can detect a HTTP response line and replace that with a custom one. header( "HTTP/1.1 404 Not Found" );
Methods to Set HTTP Status Code Sr.No. This method sets an arbitrary status code. The setStatus method takes an int (the status code) as an argument. If your response includes a special status code and a document, be sure to call setStatus before actually returning any of the content with the PrintWriter.
Status codes are similar in that they give information about if a page has loaded successfully or not, and the root cause of any errors. PHP is a scripting language that can generate status-code data.
Maybe you already sent some output before calling http_response_code(). It causes HTTP 200 silently with no warning (it does not emit well known headers are already sent). You can send some output but you can not exceed value of php directive output_buffering
(see your phpinfo page). Usually it is set to 4096 bytes (4kB). Try to temporary increase output_buffering
in php.ini to much higher value (do not forget to restart webserver). Note that output_buffering
is type PHP_INI_PERDIR
and can not be changed at runtime e.g. via ini_set().
PHP_INI_PERDIR: Entry can be set in php.ini, .htaccess, httpd.conf or .user.ini
I recommend to use integer instead of string: http_response_code(400)
... just to be consistent with PHP doc. But http_response_code()
works well also with strings - I have tested it now, so string does not cause your problem as @DiabloSteve indicates in comments.
You need to not return Your function as You did:
return "error";
Answer
You need to exit Your function like this:
http_response_code(400);
exit;
Also echo
and the error code like a string is redundant
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With