user8774850
user8774850

Reputation:

How to use password_hash for CodeIgniter

I am studying the CodeIgniter framework and trying to build a login and registration system. In the bottom are two functions in the controllers for login and registration.

People suggest me using "'password' => password_hash($this->input->post('password'), PASSWORD_BCRYPT, $options)," instead of MD5 for password. I tried to do that but not works.

Can you guys help me with this? Do I need change anything else in my model or view? Thank you guys very much

Controllers: Login function

if($this->input->post('loginSubmit')){
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
        $this->form_validation->set_rules('password', 'password', 'required');
        if ($this->form_validation->run() == true) {
            $con['returnType'] = 'single';
            $con['conditions'] = array(
                'email'=>$this->input->post('email'),
                'password' => md5($this->input->post('password')),
                'status' => '1'
            );

            $checkLogin = $this->user->getRows($con);
            if($checkLogin){
                $this->session->set_userdata('isUserLoggedIn',TRUE);
                $this->session->set_userdata('userId',$checkLogin['id']);
                redirect('users/account');
            }else{
                $data['error_msg'] = 'Wrong email or password, please try again.';
            }
        }
    }

registration function

$data = array();
    $userData = array();

    if($this->input->post('regisSubmit')){
        $this->form_validation->set_rules('name', 'Name', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_email_check');
        $this->form_validation->set_rules('password', 'password', 'required');
        $this->form_validation->set_rules('conf_password', 'confirm password', 'required|matches[password]');

        $userData = array(
            'name' => strip_tags($this->input->post('name')),
            'email' => strip_tags($this->input->post('email')),
            'password' => md5($this->input->post('password')),
            'gender' => $this->input->post('gender'),
            'phone' => strip_tags($this->input->post('phone'))
        );

        if($this->form_validation->run() == true){
            $insert = $this->user->insert($userData);
            if($insert){


                $this->session->set_userdata('email',$userData['email']);
                redirect('email');
            }else{
                $data['error_msg'] = 'Some problems occured, please try again.';
            }

And here is my getRows function in the models.

    function getRows($params = array()){
    $this->db->select('*');
    $this->db->from($this->userTbl);


    //fetch data by conditions
    if(array_key_exists("conditions",$params)){
        foreach ($params['conditions'] as $key => $value) {
            $this->db->where($key,$value);
        }
    }

    if(array_key_exists("id",$params)){
        $this->db->where('id',$params['id']);
        $query = $this->db->get();
        $result = $query->row_array();
    }else{
        //set start and limit
        if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
            $this->db->limit($params['limit'],$params['start']);
        }elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
            $this->db->limit($params['limit']);
        }
        $query = $this->db->get();
        if(array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
            $result = $query->num_rows();
        }elseif(array_key_exists("returnType",$params) && $params['returnType'] == 'single'){
            $result = ($query->num_rows() > 0)?$query->row_array():FALSE;
        }else{
            $result = ($query->num_rows() > 0)?$query->result_array():FALSE;
        }
    }

    //return fetched data
    return $result;
}

Upvotes: 1

Views: 11865

Answers (3)

Gufran Hasan
Gufran Hasan

Reputation: 9381

You can do it by using password_hash() function in CodeIgniter. password_hash

// create a function custom_password_hash()
private function custom_password_hash($pass){
   return password_hash($pass, PASSWORD_BCRYPT);
}

Now you can call this from anywhere within the same Controller as:

$userData = array(
            'name' => strip_tags($this->input->post('name')),
            'email' => strip_tags($this->input->post('email')),
            'password' =>$this->custom_password_hash($this->input->post('password')),
            'gender' => $this->input->post('gender'),
            'phone' => strip_tags($this->input->post('phone'))
        );

Hope this will make sense for you.

Upvotes: 1

Pradeep
Pradeep

Reputation: 9707

Hope this will help you :

in registration : hash password during registration like this with : password_hash

$userData = array(
        'name' => strip_tags($this->input->post('name')),
        'email' => strip_tags($this->input->post('email')),
        'password' => password_hash($this->input->post('password'),PASSWORD_DEFAULT),
        'gender' => $this->input->post('gender'),
        'phone' => strip_tags($this->input->post('phone'))
    );

In login : check password using password_verify in login

/*get the user data based on email or whatever your condition is but exclude password here*/

/* your condition here 
$con['email'] = $email;
$con['status'] = 1; or whatever you set in $con
*/
$checkLogin = $this->user->getRows($con);
if($checkLogin)
{
    if (password_verify($password,$checkLogin['password']))
    {
        $this->session->set_userdata('isUserLoggedIn',TRUE);
        $this->session->set_userdata('userId',$checkLogin['id']);
        redirect('users/account');
    }

}
else
{
     $data['error_msg'] = 'Wrong email or password, please try again.';
}

Your model's method getRows() should be like this :

public function getRows($where = array())
{
    if (! empty($where))
    {
       $this->db->where($where);
       $query = $this->db->get('users');
       if ($query->num_rows() > 0)
       {
          return $query->row_array();
       } 
     }
     else
     {
         $query = $this->db->get('users');
         if ($query->num_rows() > 0)
         {
            return $query->result_array();
         } 
     }
}

for more : http://php.net/manual/en/function.password-hash.php

Upvotes: 1

Karlo Kokkak
Karlo Kokkak

Reputation: 3714

md5() to password_hash() for better password encryption.

In register controller:

Change:

'password' => md5($this->input->post('password')),

To:

'password' => password_hash($this->input->post('password'),PASSWORD_DEFAULT),

In login controller - removed password as condition for $this->user->getRows(..) and subsequently added password_verify() to login check.

Make sure $checkLogin['password'] is also returned from $this->user->getRows($con) for password_verify(..) to work.

Updated Code:

if($this->input->post('loginSubmit')){
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
        $this->form_validation->set_rules('password', 'password', 'required');
        if ($this->form_validation->run() == true) {
            $con['returnType'] = 'single';
            $con['conditions'] = array(
                'email'=>$this->input->post('email'),
                'status' => '1'
            );

            $checkLogin = $this->user->getRows($con); // assumes 'password' field is also returned..
            if(password_verify($this->input->post('password'), $checkLogin['password']){
                $this->session->set_userdata('isUserLoggedIn',TRUE);
                $this->session->set_userdata('userId',$checkLogin['id']);
                redirect('users/account');
            }else{
                $data['error_msg'] = 'Wrong email or password, please try again.';
            }
        }
    }

Upvotes: 0

Related Questions