Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Response Status Code [duplicate]

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' );   } 
like image 263
Rob Wilkerson Avatar asked May 28 '11 19:05

Rob Wilkerson


People also ask

What is the HTTP status code for duplicate record?

409 Conflict - Client attempting to create a duplicate record, which is not allowed. 410 Gone - The requested resource has been deleted. 411 Length Required - The server will not accept the request without the Content-Length Header.

What is a 207 response?

207: Multi-Status The 207 Multi-Status status code provides status for multiple independent processes and used by WebDAV servers. The default message/response is a text/XML message. It indicates that multiple operations have taken place and that the status for each operation can be viewed in the body of the response.

What is a 201 response code?

The HTTP 201 Created success status response code indicates that the request has succeeded and has led to the creation of a resource.


2 Answers

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.

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

PHP >=5.4

See Gajus' answer: https://stackoverflow.com/a/14223222/362536

like image 197
Brad Avatar answered Sep 21 '22 08:09

Brad


Since PHP 5.4 you can use http_response_code.

http_response_code(404); 

This will take care of setting the proper HTTP headers.

If you are running PHP < 5.4 then you have two options:

  1. Upgrade.
  2. Use this http_response_code function implemented in PHP.
like image 31
Gajus Avatar answered Sep 21 '22 08:09

Gajus