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
Upon revisiting this question, and reading Adriano's comment on my previous answer (regarding redirecting the user to a friendly page), I have come up with a new solution.
Within a controller you can call
$this->cakeError('error404')
to generate a friendly 404 page. This can can be customised (as with other errors) by creating file at 'app/views/errors/error404.ctp
'.After having a closer look at the code for
cakeError
, my recommendation is to try extending Cake'sErrorHandler
by creating a file at 'app/error.php
' or (possibly more preferable) 'app/app_error.php
'.The code for your
error403
(mimicking theerror404
code) could read as follows:You should also be able to provide a custom view for this error by creating '
app/views/errors/error403.ctp
'. Here is a modified version of the error404 view: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.
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:
Notes concerning CakePHP 3.x seem to be missing, so to make this thread complete:
For CakePHP 3.x use:
For versions before CakePHP 3.3.x you can use the same style as CakePHP 2.x:
Note that using the PHP function directly also works (
http_response_code(403); die();
), though using the response object seems like the intended method.