2013-07-29 68 views
0

我在我的UsersController.php文件中创建了一个方法,以便我的用户可以更改其密码。 我的方法PHP代码为:cakephp - 更改密码方法留空数据库中的密码字段

public function changepass() { 
    $this->User->id = $this->Auth->user('id'); 
    if($this->User->exists()) {   
     $new_pass = $this->request->data['User']['newpass']; 
     $repeat_pass = $this->request->data['User']['newrepeat']; 
     if($new_pass == $repeat_pass) { 
      $this->User->saveField('password',$new_pass); 
      $this->Session->setFlash(__('Updated successfully')); 
      $this->redirect(array('controller' => 'users','action' => 'dashboard')); 
     } else { 
      $this->Session->setFlash(__('Passwords did not match')); 
      $this->redirect(array('controller' => 'users','action' => 'changepass')); 
     } 

    } 
} 

和我changepass.ctp查看文件是:

<?php 
    echo $this->Form->create(); 

    echo $this->Form->input('newpass',array('type'=>'text','label'=>array('text'=>'Enter new password'))); 

    echo $this->Form->input('newrepeat',array('type'=>'text','label'=>array('text'=>'Confirm new password'))); 
?> 

    <button type="submit">Save</button> 

<?php echo $this->Form->end(); ?> 

当我尝试的用户/ changepass下浏览,它返回了大约一个不确定的指数2个错误:

Notice (8): Undefined index: User [APP/Controller/UsersController.php, line 108] 

Notice (8): Undefined index: User [APP/Controller/UsersController.php, line 109] 

在我的代码,这部分指出:

$new_pass = $this->request->data['User']['newpass']; 
    $repeat_pass = $this->request->data['User']['newrepeat']; 

并且它(立即)将我的数据库中的用户密码更改为空白。

我找不出有什么问题。如果你能在这一点上帮助我,我将非常感激。

预先感谢您。

+1

为什么''而不是表单助手提交按钮?但是造成你的问题的原因是在POST上缺少检查! PS:我推荐http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp/ - 这个主题的干净方法。 – mark

回答

2

您忘记了关于控制器中表单处理的一个重要部分:检查POST。

if ($this->request->is('post')) { 
    // only then try to access $this->request->data['User'] content! 
} 

在不是帖子(get)的情况下,您只需显示表格 - 尤其是不用保存任何东西。

提示:看看烘焙代码(使用蛋糕烘烤),你会看到它是如何正确完成的。

+0

谢谢,这是它!但为什么后检查至关重要? –

+1

,因为该操作同时用于GET和POST。如果没有检查并且只是执行save(),那么您的操作就会变成垃圾。 – mark

+0

我想我明白了,谢谢! –