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?
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?
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
The reason you get a persistent 200 ok response code, is because you have some enters (newlines) before you have your php tag :
line 1 line 2
and this can also be between php tags:
line 1 line 2
Make sure to remove these enters or else these newlines will be considered as output. This is why any http_response_code(xxx) you throw in after that has no impact because the newline output represent a '200 ok' response. I have simulated your problem with r-client (should be the same as postman on chrome).
In my case it was
<pre>
<?php
http_response_code(404);
?>
</pre>
this code returns 200, because pre tag already sent, before php started
<?php
http_response_code(404);
returns 404 successfully because no content sent yet.
even a space is not allowed before <?php otherwise will return 200
You need to call http_response_code
twice like this
http_response_code(400); // this will get previous response code 200 and set a new one to 400
echo http_response_code(); // this will get previous response code which is now 400
return;