停止在cakepp中更新字段


stop field to being update in cakephp

在我的蛋糕PHP应用程序中,我有一个编辑表单,其中"电子邮件"字段是只读的,这意味着用户不能更新它。不,如果我认为从安全角度来看,用户可以通过"firebug"或其他一些浏览器插件来更新字段。

我正在使用$this->User->save($this->data)保存更新的数据。通过此功能,还可以更新电子邮件。

我们在cakephp中有什么方法可以防止这个字段被更新,比如在这里传递一个参数或类似的东西吗?

您可以简单地从$this->data:中删除电子邮件字段

unset($this->data['User']['email']);
$this->User->save($this->data);

您可以执行以下操作:

$dontUpdateField = array('email');
$this->Model->save(
           $this->data, 
           true, 
           array_diff(array_keys($this->Model->schema()),$dontUpdateField)
);

如果安全性是一个问题,只需拒绝任何具有意外值的数据。在蛋糕中,你可以这样做,但它可以适用于任何框架/cms

/**
 * Checks input array against array of expected values.
 *
 * Checks single dimension input array against array of expected values.
 * For best results put this is in app_controller.
 *
 * @param array $data - 1 dimensional array of values received from untrusted source
 * @param array $expected - list of expected fields
 * @return boolean - true if all fields are expected, false if any field is unexpected.
 */
protected function _checkInput($data,$expected){
  foreach(array_keys($data) as $key){
    if (!in_array($key,$expected)){
     return;
    }
  }
  return true;
}
/** 
 * edit method.
 * 
 * put this in <Model>_controller
 * @param string $id
 * @return void
 * @todo create errors controller to handle incorrect requests
 * @todo configure htaccess and Config/routes.php to redirect errors to errors controller
 * @todo setup log functionality to record hack attempts
 * @todo populate $expected with fields relevant to current model
 */ 
function edit($id=null){
  $expected = ('expectedVal1', 'expectedVal2');
  $this->Model->id = $id;
  if (!$this->Model->exists()) {
    throw new NotFoundException(__('Invalid model'));
  }
  if ($this->request->is('post')) {
    if (!$this->_checkData($this->request->data['Model'], $expected)) {
      //log the ip address and time
      //redirect to somewhere safe
      $this->redirect(array('controller'=>'errors','action'=>'view', 405);
    }
    if ($this->Model->save($this->request->data)) {
      //do post save routines
      //redirect as necessary
    }
    else {
      $this->Session->setFlash(__('The model could not be saved. Please, try again.'));
    }
  }
  $this->set('model',$this->Model->read($expected,$id));
}

您可以使用安全组件并隐藏电子邮件。使用此组件时,隐藏字段无法更改,否则蛋糕会使表单变黑。

http://book.cakephp.org/1.3/en/view/1296/Security-Component

如果你的应用程序是公共的,强烈建议你使用安全性,否则通过在表单上提交额外的字段来在模型中注入数据是有点琐碎的,当你执行$this->Model->save($this->data))时,额外的字段会被保存,除非你做额外的工作来验证$this->数据的每个字段;