Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http_response_code() not working, always output 200

Tags:

php

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?

like image 239
Benjamin W Avatar asked Jan 24 '18 09:01

Benjamin W


People also ask

What is Http_response_code in PHP?

The http_response_code() function sets or returns the HTTP response status code.

How do I get HTTP response in PHP?

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" );

How do you set a status code in HTTP response?

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.

What is PHP status code?

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.


2 Answers

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.

like image 142
mikep Avatar answered Sep 19 '22 05:09

mikep


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

like image 20
Claudio Ferraro Avatar answered Sep 20 '22 05:09

Claudio Ferraro