Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you specify an HTTP status code in Cakephp?

Tags:

cakephp

In my controller, I check a condition to see if the user is allowed to do something. If the check fails, I want to send a 403 back to the browser. How do I do that in Cakephp?

like image 559
allyourcode Avatar asked Jul 08 '09 22:07

allyourcode


People also ask

How do you set a status code in HTTP response?

Methods to Set HTTP Status Code Sr.No. This method sets an arbitrary status code. The setStatus method takes an int (the status code) as an argument. If your response includes a special status code and a document, be sure to call setStatus before actually returning any of the content with the PrintWriter.

How can I get HTTP status code?

Just use Chrome browser. Hit F12 to get developer tools and look at the network tab. Shows you all status codes, whether page was from cache etc.

Can I use custom HTTP status codes?

Yes, as long as you respect the class -- that is, 2xx for success, 4xx for Client error, etc. So you can return custom 4XX error codes (preferably those that are unassigned) for your own application's error conditions.

What is HTTP status code in API?

The status codes are divided into five categories. 1xx: Informational – Communicates transfer protocol-level information. 2xx: Success – Indicates that the client's request was accepted successfully. 3xx: Redirection – Indicates that the client must take some additional action in order to complete their request.


1 Answers

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'); 
like image 172
deizel Avatar answered Oct 04 '22 00:10

deizel