http_response_code() not working, always output 200
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