Alex Campkin
Alex Campkin

Reputation: 29

PHP Username And Password Verification using password_verify

Im currently trying to update my insecure login system. However cannot figure out how to incorporate an if (password_verify.. command.

Any help would be most appreciated.

//Create query
$qry="SELECT * FROM user WHERE username='$username' AND password='$password'";
$result=mysql_query($qry);
if($result) {
    if(mysql_num_rows($result) > 0) {
    //IF Login Successful
        session_regenerate_id();
        $user = mysql_fetch_assoc($result);
        $_SESSION['SESS_USER_ID'] = $user['user_id'];
        $_SESSION['SESS_FIRST_NAME'] = $user['username'];
        $_SESSION['SESS_LAST_NAME'] = $user['password'];
        session_write_close();
        header("location: home.php");
        exit();
    }else {
        //IF Login failed
        $errmsg_arr[] = 'user name and password not found';
        $errflag = true;
        if($errflag) {
            $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
            session_write_close();
            header("location: index.php");
            exit();
        }
    }

Upvotes: 0

Views: 1007

Answers (1)

Answers_Seeker
Answers_Seeker

Reputation: 468

Hereafter the answer of your question and some general information:

The password verify function:

A good practice is to encrypt sensitive data before storing them. As you don't want people with bad intentions to be able to retrieve passwords you'll use an asymetric (one way) encryption algorithms family which we call hash.

You'll check if the user gave you the right credentials by re-generating the hash using the inputted value and compare it to the one stored in your Database.

In this scenario, you are not inserting any user input in your query.

You can add complexity in the hash generation by adding a salt.

The password_hash documentation is pretty explicit and you'll find in this link an SO discussion about hash algorithms.

The account creation/password change step:

  • Compute the user's password hash
  • Store it in the database

To summarize the authentication step:

  • retrieve to user input
  • call the password_verify($user_password_inputed, $hash_retrieved_from_db) function
  • If the function returned true, then the user is authenticated

SQL injection and user input:

Why is it disadvised to insert user input in a query ?

You shouldn't insert user input in a query because of SQL injection which is a way for the user to make your database execute his own query. Using the injection he can display or update some data whereas he shouldn't be allowed to.

Preventing injections

To prevent injections, the idea is to sanitize/insure that the user input doesn't contain a malicious query/instructions.

Nowadays, we have tools like PDO which handle these issues by using the prepared statements.

Upvotes: 2

Related Questions