【问题标题】:How to validate a POST of a non standard action in Cake PHP 1.3如何在 Cake PHP 1.3 中验证非标准操作的 POST
【发布时间】:2011-10-09 14:50:06
【问题描述】:

使用 CakePHP 1.3

我有一个非标准动作名称的控制器 - 比如说:

class WidgetsController extends AppController {

function modifyColor($id = null) {
// Some code that modifies the background color of a widget 
}

}

和一个伴随视图views/widgets/modifyColor.ctp

modifyColor 模板 POST 到动作:

echo $this->Form->create('User',array('url' => array('controller' => 'widgets', 'action' => 'modifyColor')));

我在 POST 上收到 404,因为 CakePHP 安全组件正在尝试验证表单 我希望能够验证 POST。

我可以让它工作的唯一方法似乎是关闭 POST 验证

 if ($this->action == 'modifyColor') {
    $this->Security->validatePost = false;
}

这似乎是一个糟糕的解决方案。

如何在非标准操作中使用安全组件? allowedActions 似乎不起作用 谢谢 丹尼

回答我自己的问题。

A.在 CakePHP 中使用任意命名的动作没有问题 B. CakePHP 的一个概念性错误,涉及对表单 GET 和表单 POST 使用相同的函数

在 GET 表单上我有这个:

    if (empty($this->data)) {
          $this->data = $this->Widget->read(null, $id);
    }

表单本身有一些类似这样的代码:

      echo $this->Form->input('id');
      echo $this->formView('Current color', 'CurrentColor');
      echo $this->formView('New color',     'NewColor');
      echo $this->formView('New background color', 'BackgrdColor');

这很好,只是这些字段都没有出现在 Widget 模型中——CakePHP 安全组件将此解释为一种 XSRF 攻击——因为它正在查找不属于模型的表单中的字段。这就是为什么:

 $this->Security->validatePost = false;

解决了“问题”。

正确的解决方案是不要在控制器操作中使用模型填充 $this->data 并在 POST 上处理字段分配:

function modcolor () {
    $this->layout = 'app_ui_listview';
    if (!empty($this->data)) {
          $id = $this->Session->read('Auth.User.id');
          $u = $this->Widget->read(null, $id);
                 // Assign fields from the form to the model....


    }
}

【问题讨论】:

  • 你应该使用 echo $this->Form->create('Widget',array('url' => array('controller' => 'widgets', 'action' => 'modifyColor ')));而不是 echo $this->Form->create('User',array('url' => array('controller' => 'widgets', 'action' => 'modifyColor')));

标签: security cakephp components cakephp-1.3


【解决方案1】:

问题是您正在尝试传递 url,并且您也在尝试传递控制器的东西。

echo $this->Form->create('Widget', array('controller' => 'widgets', 'action' => 'modifyColor'));

echo $this->Form->create('Widget', array('url' => '/widgets/modifyColor'));

【讨论】:

  • 在第一个版本中,controller 键会被忽略(只有action 键会起作用),第二个版本相当于问题中的代码:echo $this->Form->create('User',array('url' => array('controller' => 'widgets', 'action' => 'modifyColor')));。或者:不幸的是,您的答案不正确 - url 键是有效的,并且在 CakePHP 中将 url 指定为数组是正常的。尽管问题的状态,这个问题已经解决了 - 请参阅问题中的Answering my own question.
猜你喜欢
  • 1970-01-01
  • 2012-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-24
  • 2014-06-27
  • 1970-01-01
  • 2021-03-08
相关资源
最近更新 更多