Question

In yii I am creating password reset functionality by using a security question. First the user needs to enter his email id. I created emailform.php in views->User1 as

<?php
$form=$this->beginWidget('CActiveForm', array(
    'id'=>'email-form',
    'enableClientValidation'=>true,
    ));
echo CHtml::textField('email');
echo CHtml::submitButton('Send');
$this->endWidget();

In controller I created method as

public function actionPassword() {
    if (isset($_POST['email'])) {
       $email = $_POST['email'];
       //process email....
       //....
    }
    $this->render('_emailForm');
}

Now I want to check whether this email id exists in User table. If it does, then I want to display a security question to him. How can I implement this?

Was it helpful?

Solution

This will help you get started, you would put a method similar to this in your controller and create a view with a password field on it.

public function actionPassword() {
  if(isset($_POST['email'])) {
    $record=User::model()->find(array(
      'select'=>'email',
      'condition'=>'email=:email',
      'params'=>array(':email'=>$_POST['email']))
    );

    if($record===null) {
      $error = 'Email invalid';
    } else {
      $newpassword = 'newrandomgeneratedpassword';
      $record->password = $this->hash_password_secure($newpassword);
      $record->save(); //you might have some issues with the user model when the password is protected for security
      //Email new password to user
    }
  } else {
    $this->render('forgetPassword'); //show the view with the password field
  }
}

OTHER TIPS

If you are using CActiveRecords, the proper way to check whether a record exists is by using exists() function, not find() function.

$condition = 'email_d=:emailId';
$params = array(':emailId' => $emailId);
$emailExists = User::model()->exists($condition,$params);
if( $emailExists) )
{
  //email exists
}
else
{
  // email doesn't exist
}

To check record in database you can with two options

$exists = ModelName::find()->where([ 'column_name' => $value])->andWhere(['column_name' => $value])->exists();
//returns true or false

and

$exists = ModelName::findOne(["column_name" => $value,"column_name"=>$value]);

check

if ($exists)
{
// exit
}
else
{
// not exist
}
$model = YourModel::model()->find('email = :email', array(':email' => $_POST['email']));

This used like PDO:

$query = 'SELECT * etc.. WHERE email = :email';

$stmt = DB::prepare($query);
$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->execute();

etc...

It is not safe?!

And then..

if( empty($model) )
{
  // exit code
}
else
{
  // success block
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top