设置响应状态代码

我有一个 API 调用,我需要能够运行一些检查,并可能返回各种状态代码。我不需要自定义视图或任何东西,我只需要返回适当的代码。如果用户没有传递正确的凭据,我需要返回一个401状态。如果他们没有发送支持的请求格式,我需要返回一个400状态。

因为它是一个 API,所以我真正想做的就是设置响应状态,然后用一个简单的、愚蠢的消息来说明请求为什么失败(可能使用 exit)。只够完成任务,但我一直没办法让它正常工作。我已经尝试使用 PHP 的 header()和 Cake 的 $this->header()(这都在控制器中) ,但是尽管我得到了退出消息,但是标题显示了 200 OK状态。

使用下面的代码,我得到了消息,但是头部没有设置。我遗漏了什么?

  if( !$this->auth_api() ) {
header( '401 Not Authorized' );
exit( 'Not authorized' );
}
138585 次浏览

I don't think you're setting the header correctly, try this:

header('HTTP/1.0 401 Unauthorized');

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

I had the same issue with CakePHP 2.0.1

I tried using

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

and

$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.

Why not using Cakes Response Class? You can set the status code of the response simply by this:

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

Then just render a file with the error message, which suits best with JSON.

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.

As written before, but for beginner like me don't forget to include the return.

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