How do you specify an HTTP status code in Cakephp?
EDIT - This question is quite old and covers different versions of the CakePHP framework. Following is a summary of which version each answer applies to. Don't forget to vote on the solution that helps most.
- CakePHP 3.x and 4.x - using response object (Roberto's answer)
- CakePHP 2.x - using exceptions (Brad Koch's answer) [preferred solution]
- CakePHP 2.x - setting header only (Asa Ayers' answer)
- CakePHP 1.x - using error handler (my other answer)
- CakePHP 1.x - setting header only (this answer)
EDIT #2 - A more detailed answer for CakePHP 2.x has been added by Mark37.
EDIT #3 - Added solution for CakePHP. (May 2018: CakePHP 3.5 did some function renaming, solution by Roberto is still valid.)
By looking at the relevant API code from the previous comment, it seems you can call Controller::header($status) to output a header without redirection. In your case, the proper usage is most likely:
$this->header('HTTP/1.1 403 Forbidden');
$this->response->statusCode(403);
Will set the status code when Cake is ready to send the response. CakeResponse::send() expects to send the status code and message, so in my tests I think my using header()
was getting overwritten. using $this->header('HTTP/1.1 400 Bad Request')
doesn't work either because Cake expects any call to $this->header
to be split on a colon ex: $this->header('Location: ...')
Notes concerning CakePHP 3.x seem to be missing, so to make this thread complete:
For CakePHP 3.x and 4.x use:
$response = $this->response->withStatus(403);
return $response;
For versions before CakePHP 3.3.x you can use the same style as CakePHP 2.x:
$this->response->statusCode('code');
Note that using the PHP function directly also works (http_response_code(403); die();
), though using the response object seems like the intended method.