Search code examples
phpcodeigniterpasswordsmd5

Codeigniter : Change password for logged in user and for password that uses md5


I want to ask how to change password for logged in user, I can change the password when I enter password that matches anyone in database. For just example, user have "admin" password, I just enter the current password, new password and confirm password.

Current password: admin New Password: newadmin Current Password: new admin

And also I don't know how to change the password if the password uses md5(). I hope you can help me, I am a newbie on Codeigniter. I search answers but I really don't understand it so I want to comment but it's required 50 reputation so I post new question.

Here's my code :

Controller

    public function update(){
    $this->form_validation->set_rules('password', 'Current Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
    $this->form_validation->set_rules('newpass', 'New Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
    $this->form_validation->set_rules('confpassword', 'Confirm Password', 'required|alpha_numeric|min_length[6]|max_length[20]');

    if($this->form_validation->run()){
        $cur_password = $this->input->post('password');
        $new_password = $this->input->post('newpass');
        $conf_password = $this->input->post('confpassword');
        $this->load->model('queries');
        $userid = '1';
        $passwd = $this->queries->getCurrPassword($userid);
        if($passwd->password == $cur_password){
            if($new_password == $conf_password){
                if($this->queries->updatePassword($new_password, $userid)){
                    echo 'Password updated successfully';
                }
                else{
                    echo 'Failed to update password';
                }
            }
            else{
                echo 'New password & Confirm password is not matching';
            }
        }
        else{
            echo'Sorry! Current password is not matching';

    }
}
else{
    echo validation_errors();
}

model

 public function getCurrPassword($userid){
  $query = $this->db->where(['id'=>$userid])
                    ->get('users');
    if($query->num_rows() > 0){
        return $query->row();
    } }

  public function updatePassword($new_password, $userid){
  $data = array(
      'password'=> $new_password
      );
      return $this->db->where('id', $userid)
                      ->update('users', $data); }

Solution

  • I got a solution for my problem.

    For logged in user I just changed the $userid = '1'; into $userid = $this->session->userdata('account_id');

    And for the md5 password I just add md5 on passwords.Like what @sintakonte did and @zaph is right.

    "Only use strong password hashing algorithms like BCrypt, which is used in PHP’s own Password Hashing functions."

    Reference : https://www.codeigniter.com/userguide3/general/security.html

    Thanks for the help guys!