你如何在 Cakephp 中指定一个 HTTP 状态码? [英] How do you specify an HTTP status code in Cakephp?

查看:16
本文介绍了你如何在 Cakephp 中指定一个 HTTP 状态码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器中,我检查一个条件以查看是否允许用户执行某些操作.如果检查失败,我想将 403 发送回浏览器.我如何在 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?

推荐答案

EDIT - 这个问题很老了,涵盖了 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 - 添加了针对 CakePHP 2.x 的更详细的答案作者:Mark37.

EDIT #2 - A more detailed answer for CakePHP 2.x has been added by Mark37.

EDIT #3 - 添加了 CakePHP 的解决方案.(2018 年 5 月:CakePHP 3.5 做了一些函数重命名,Roberto 的解决方案 仍然有效.)

EDIT #3 - Added solution for CakePHP. (May 2018: CakePHP 3.5 did some function renaming, solution by Roberto is still valid.)

通过查看上一条评论中的相关API 代码,看来你可以调用 Controller::header($status) 来输出一个没有重定向的标头.在您的情况下,最有可能的正确用法是:

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');

这篇关于你如何在 Cakephp 中指定一个 HTTP 状态码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆