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?
相关问题
- Change input value based on another input's va
- How to implement og:tag in each post?
- How to validate single field of a model in cakephp
- CakePHP: add/substract with save()?
- How to save multiple records in cakephp 3
相关文章
- How to force refresh of images & css files in Cake
- Cookie vs. Session based flash message
- CakePHP and GROUP BY
- CakePHP: Cannot modify header information - header
- CakePHP 3.0 Flash Message
- cakephp login redirect
- Conditional Component Loading in CakePHP
- how to get Video id from iframe of youtube in php
In CakePHP 2, the preferred method is to throw an exception:
Perhaps something in this section of the cakephp manual can help you.
I'm adding in my two cents here because I don't feel like any of these answers covered this topic as thoroughly as I would have liked (at least for Cake 2.x).
If you want to throw an error status, use the Exception classes (as mentioned in other answers):
Fun fact: Cake will automatically do some magical error rendering even for RESTful calls via the
ExceptionRenderer
class. Even more fun of a fact is that it's based on the Status Code, not the fact that anException
might have been thrown, so if you set the status code to > 400 on your own you will likely get error messages even if you didn't want them.If you want to return a specific status code for a REST JSON/XML endpoint, take advantage of the new
CakeResponse
object, but also make sure that you add the special_serialize
variable or you'll end up with a 'view not found' error as cake will attempt to find a view to render your JSON/XML. (This is by design - see theJsonView
/XmlView
class.)And lastly, if you want to send a non-200 status for a regularly rendered page, you can just use the
setStatus()
method with nothing else as mentioned in a previous answer:UPDATE:
is no longer available. Use
You can use cakephp
response
for custom message:It has changed again since CakePHP 3.6:
Use now
instead of
https://api.cakephp.org/3.7/class-Cake.Controller.Controller.html#_setResponse
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: ...')