Set response status code

I have an API call for which I need to be able to run some checks and possibly return various status codes. I don't need custom views or anything else, I just need to return the correct code. If the user did not provide the correct credentials, I need to return the status of 401. If they did not send a supported request format, I need to return the status of 400.

Since this is an API, all I really want to do is set the status of the response and exit with a simple, stupid message about why the request failed (possibly using exit ). Enough to do this work, but I could not get it to work correctly. I tried using PHP header() and Cake $this->header() (all in the controller), but although I get an exit message, the header shows a status of 200 OK .

Using the following code, I get a message, but the header is not set. What am I missing?

  if( !$this->auth_api() ) { header( '401 Not Authorized' ); exit( 'Not authorized' ); } 
+80
May 28 '11 at 19:44
source share
6 answers

PHP <= 5.3

The header() function has a parameter for the status code. If you specify it, the server will take care of it from there.

 header('HTTP/1.1 401 Unauthorized', true, 401); 

PHP> = 5.4

See Gayus's answer: https://stackoverflow.com/a/316877/

+112
May 28 '11 at 20:59
source share

With PHP 5.4 you can use http_response_code .

 http_response_code(404); 

This will take care of setting the correct HTTP headers.

If you use PHP <5.4, then you have two options:

+95
Jan 08 '13 at 20:12
source share

I do not think you are setting header correctly, try the following:

 header('HTTP/1.0 401 Unauthorized'); 
+10
May 28 '11 at 19:53
source share

Why not use the Cakes Response Class? You can set the response status code simply as follows:

 $this->response->statusCode(200); 

Then just visualize the file with the error message that works best for JSON.

+10
Aug 18 '12 at 10:55
source share

I had the same problem with CakePHP 2.0.1

I tried to use

 header( 'HTTP/1.1 400 BAD REQUEST' ); 

and

 $this->header( 'HTTP/1.1 400 BAD REQUEST' ); 

However, none of them solved my problem.

I eventually resolved it with

 $this->header( 'HTTP/1.1 400: BAD REQUEST' ); 

After that, there are no errors or warnings from php / CakePHP.

* edit: In the last call to the $this->header function, I put a colon ( : between 400 and the error description text.

+4
Nov 21 '11 at 10:44
source share

As written earlier, but for beginners like me, remember to enable refunds.

 $this->response->statusCode(200); return $this->response; 
+2
Feb 01 '15 at 10:58
source share



All Articles