Search code examples
codeigniterpasswordsverify

Codeigniter password_verify method


I have this method in my Codeigniter (version 3.0) login module. It works fine but is this safe? Is any better solution to check login and password using PHP password_verify? (PHP 5.6, MySQL 5.0).

        $user = $this->input->post('username');
        $password = $this->input->post('password');
        $myquery = $this->db->query("SELECT * FROM users WHERE user = '$user'");
        $row = $myquery->row();

        if (isset($row))
        {
            //Using hashed password - PASSWORD_BCRYPT method - from database
            $hash = $row->password;


            if (password_verify($password, $hash)) {

                echo 'Password is valid!';


            } else {

                echo 'Invalid password.';

            }


        } else{

            echo 'Wrong user!';
        }

Solution

  • your code looks fine but you can do it a bit more in a CI Way and a bit more cleaner, in this case you are protected by sql injections and you have a bit more encapsulation

    Try something like this:

    public function checkLogin()
    {
        $this->load->library("form_validation");
    
        $arrLoginRules = array
        (
            array(
                "field" => "username",
                "label" => "Benutzername",
                "rules" => "trim|required"
            ),
            array(
                "field" => "password",
                "label" => "Passwort",
                "rules" => "trim|required"
            )
    
        );
    
        $this->form_validation->set_rules($arrLoginRules);
    
        try
        {
            if (!$this->form_validation->run()) throw new UnexpectedValueException(validation_errors());
    
            $user = $this->input->post('username');
            $password = $this->input->post('password');
            $query = $this->db
                ->select("*")
                ->from("users")
                ->where("user", $user)
                ->get();
    
            if ($query->num_rows() != 1)    throw new UnexpectedValueException("Wrong user!");
    
            $row = $query->row();
            if (!password_verify($password, $row->hash)) throw new UnexpectedValueException("Invalid password!");
    
            echo "valid user";
    
        }
        catch(Excecption $e)
        {
            echo $e->getMessage();
        }
    }
    

    Fore more information, take a look at the Form validation and the Query Builder documentation.