大家好,我正在使用cakephp 2.x,因为我是这里的新手,在将密码存储到数据库之前,我需要先对其进行加密
User.ctp:我要像这样发布
<?php
echo $this->Form->input('password',array('type'=>'password','label'=>false,'div'=>false,'class'=>'form-control','id'=>'password'));
?>
控制器:
public function setting()
{
$this->layout='setting_template';
if($this->Session->read('username')==""){
$this->redirect(array('action' => 'user_login'));
}
elseif ($this->Session->read('username') == "admin" )
{
if($this->request->is('post'))
{
$this->data['password'] = encrypt($this->data ['password']);
if ($this->Login->save($this->request->data)) {
$this->Session->setFlash('The user has been saved');
$this->redirect(array('action' => 'setting'));
} else {
$this->Session->setFlash('The user could not be saved. Please, try again.');
}
}
$opp=$this->Login->find('all');
$this->set('login',$opp);
}
else{
echo "<script type='text/javascript'> alert('Permission Denied'); </script>";
$this->redirect(array('action' => 'index'));
}
}
登录控制器:
public function login()
{
$this->layout='login_template';
if($this->data)
{
$this->Session->write('id',$this->data['Login']['id'] );
$results = $this->Login->find('first',array('conditions' => array('Login.password' => $this->data['Login']['password'],'Login.username' => $this->data['Login']['username'])));
$this->Session->write('name',$results['Login']['name']);
if ($results['Login']['id'])
{
$this->Session->write($this->data['Login']['username'].','. $this->data['Login']['password']);
$this->Session->write('username',$this->data['Login']['username']);
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setFlash("error");
}
}
我如何加密密码文件以及如何使用模型
在使用时,CakePhp
请遵循框架的最佳做法。
创建新的用户记录时,可以使用适当的密码哈希器类在模型的beforeSave回调中哈希密码:
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
public function beforeSave($options = array()) {
if (!empty($this->data[$this->alias]['password'])) {
$passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
}
致电之前,您无需对密码进行哈希处理$this->Auth->login()
。各种身份验证对象将分别对密码进行哈希处理。
如果您使用的模型与User
身份验证使用的模型不同,则需要在AppController中定义模型。在您的案例中,您需要在AppController中执行以下操作:
$this->Auth->authenticate = array(
'Form' => array('userModel' => 'Login')
);
如果您希望对密码进行哈希处理,请尝试以下操作:
$hashedPassword = AuthComponent::password('original_password');
请参阅此处:Cakephp密码哈希。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句