Search code examples
codeigniteremailpassword-recovery

How to reset Password Using PHP Codeigniter


Am working on a Password reset system whereby the user who forgot his password can request for password reset link by submitting his email used in registration. I successfully create the email, it sent the link and I test the link by clicking on it. The link went through and load the reset page but my problem is how to make the system recognise the user who click through and get all the details including Name, Token, email with which the system will confirm that the user is the user who requested the link.

The following is what I have done so far:

Controller

    public function preset(){
        $data['success']='';
        $data['error']='';
        include_once ('query/user_query.php');

        $this->form_validation->set_rules('email','Email','trim|required|valid_email');
         $this->form_validation->set_error_delimiters("<div class='alert alert-warning'><span type='button' class='close' data-dismiss='alert'>&times</span>","</div>");

    if($this->form_validation->run() == false){

        $this->load->view('passwordrecovery.php', $data);
    }
    else{
        $eMail = $this->input->post('email');
         $this->db->where("email = '$eMail'");
        $this->db->from("useraccount");
        $countResult = $this->db->count_all_results();


        if($countResult >=1){
           // $data['firstName'] = '';
          //  $data['lastName'] = '';
            $this->db->where("email = '$eMail'");
            $getUserData =$this->db->get("useraccount")->result();
             foreach($getUserData as $userD){

             $data['firstName'] = $userD->firstname;
             $data['lastName'] = $userD->lastname;
             }
            $sender_email = '[email protected]';
            $user_password = 'xxxxxx';
            $token = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 50);
            $subject = 'Password Reset';
            $message = '';
            $message .= "<h2>You are receiving this message in response to your request for password reset</h2>"
                    . "<p>Follow this link to reset your password <a href='".site_url()."/authenticate/resetpassword/.$token' >Reset Password</a> </p>"
                    . "<p>If You did not make this request kindly ignore!</p>"
                    . "<P class='pj'><h2>Kind Regard: Votemate</h2></p>"
                    . "<style>"
                    . ".pj{"
                    . "color:green;"
                    . "}"
                    . "</style>"
                    . "";
            // Configure email library
 $config['protocol'] = 'smtp';
 $config['smtp_host'] = 'ssl://smtp.googlemail.com';
 $config['smtp_port'] = 465;
 $config['smtp_user'] = $sender_email;
 $config['smtp_pass'] = $user_password;
 $config['mailtype'] = 'html';

 // Load email library and passing configured values to email library
 $this->load->library('email', $config);
 //$this->email->set_newline("rn");
 $this->email->set_mailtype("html");

 // Sender email address
 $this->email->from($sender_email);
 // Receiver email address
 $this->email->to($eMail);
// Subject of email
$this->email->subject($subject);
// Message in email
$this->email->message($message);

if ($this->email->send()) {

$eMail = $this->input->post('email');
$ipadd = $this->input->ip_address();
$insert = array(
  'email' => $eMail,
    'ipaddress' => $ipadd,
    'token' => $token
 );

 $this->db->insert('passwordreset', $insert);
 $mail = $this->session->set_userdata('email');
 $data['success'] = 'Email Successfully Send !';
 $this->load->view('linksent.php', $data);
 } else {
 $data['error'] =  '<p class="error_msg">Invalid Gmail Account or Password ! 
  </p>';
 }
 $this->load->view('passwordrecovery.php', $data);
  }


        if($countResult <= 0){

            //user already registered

            $data['error'] = "<div class='alert alert-warning'> Invalid 
    email address<span type='button' class='close' data- 
    dismiss='alert'>&times</span></div>";

            $this->load->view('passwordrecovery.php',$data);

        }

        }


         }

View

     <div>
                <h1>Password Recovery</h1>
                <h3>Enter your email to receive the password reset link in 
       your Inbox</h3>
                <br/>

                <?php echo form_open('authenticate/preset');?>
                <?php echo $error;?>
                <div class="form-group">
                    <input type="text" name="email" required="required">

                </div>
                <div class="form-group">
                    <input type="submit" value="Send" class="btn-success 
      btn" >
                </div>
                <?php echo form_close()?>
     <br/><br/><br/>


            </div>

Database: The following is database where I store the info:

   CREATE TABLE `passwordreset` (
   `resetid` int(11) NOT NULL,
   `email` varchar(150) NOT NULL,
   `ipaddress` varchar(25) NOT NULL,
   `token` varchar(512) NOT NULL
  ) ENGINE

The help I need is how to get the details (Name, email, token) of the user who click the link from his email and use it to validate and also use it to update his password. Thanks


Solution

  • pass user email or token in url or in hidden field when user click on verify link and check in controller method.

    <a href="<?=site_url('user_verification?user_email=' . $user_email . '&user_code=' .  $user_code);?> Click To Verifiy Email </a>
    

    user_verification controller

    public function user_verification_get()
    {
       $user_email = $this->input->get('user_email');
       $user_code = $this->input->get('user_code');
    
       $data=$this->admin_model->user_verification($user_email,$user_code);
    
       if($data)
        {
            $data['message'] = 'Success.';
        }
        else
        {
            $data['message'] = 'Not Valid User.';
        }
        $this->load->template('verify', $data);
    }
    

    Model

    public function user_verification($user_email,$user_code){
    
        $this->db->select('user_email');
        $this->db->where('user_email',$user_email);
        $this->db->where('user_code',$user_code);
        $query = $this->db->get('users');
    
        if($query->row_array() > 0)
        {
            $data['user_isactive'] = true;
    
            $this->db->where('user_email',$user_email);
            $this->db->update('users',$data);
            return $query->row_array();
        }
        return false;
    }