Codeigniter password_verify method

删除回忆录丶 提交于 2021-02-11 06:42:55

问题


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!';
        }

回答1:


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.



来源:https://stackoverflow.com/questions/39363459/codeigniter-password-verify-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!