This question already has an answer here:
- PHP: How to send HTTP response code?
header() function has a parameter for status code. If you specify it, the server will take care of it from there.
header('HTTP/1.1 401 Unauthorized', true, 401);
See Gajus’ answer: https://stackoverflow.com/a/14223222/362536
Since PHP 5.4 you can use http_response_code.
This will take care of setting the proper HTTP headers.
If you are running PHP < 5.4 then you have two options:
- Use this
http_response_codefunction implemented in PHP.
I don’t think you’re setting the header correctly, try this:
header('HTTP/1.0 401 Unauthorized');
Why not using Cakes Response Class?
You can set the status code of the response simply by this:
Then just render a file with the error message, which suits best with JSON.
I had the same issue with CakePHP 2.0.1
I tried using
header( 'HTTP/1.1 400 BAD REQUEST' );
$this->header( 'HTTP/1.1 400 BAD REQUEST' );
However, neither of these solved my issue.
I did eventually resolve it by using
$this->header( 'HTTP/1.1 400: BAD REQUEST' );
After that, no errors or warning from php / CakePHP.
*edit: In the last
$this->header function call, I put a colon (
:) between the 400 and the description text of the error.
As written before, but for beginner like me don’t forget to include the return.
$this->response->statusCode(200); return $this->response;