This question already has an answer here:
- PHP: How to send HTTP response code? 7 answers
I have an API call for which I need to be able to run some checks and potentially return various status codes. I don't need custom views or anything, I just need to return the proper code. If the user hasn't passed proper credentials, I need to return a 401 status. If they haven't sent a supported request format, I need to return a 400 status.
Because it's an API, all I really want to do is set the response status and exit with a simple, stupid message about why the request failed (probably using a exit
). Just enough to get the job done, but I haven't been able to get this to work right. I've tried using PHP's header()
and Cake's $this->header()
(this is all in the controller), but although I get the exit message, the header shows a 200 OK
status.
Using the code below, I get the message, but the header isn't set. What am I missing?
if( !$this->auth_api() ) {
header( '401 Not Authorized' );
exit( 'Not authorized' );
}
As written before, but for beginner like me don't forget to include the return.
I don't think you're setting the header correctly, try this:
PHP <=5.3
The
header()
function has a parameter for status code. If you specify it, the server will take care of it from there.PHP >=5.4
See Gajus' answer: https://stackoverflow.com/a/14223222/362536
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.
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:
http_response_code
function implemented in PHP.I had the same issue with CakePHP 2.0.1
I tried using
and
However, neither of these solved my issue.
I did eventually resolve it by using
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.