Comparing/check if correct Password from mysqli da

2019-09-21 01:22发布

问题:

I'm using:

$password = hash_hmac('sha512', 'salt' . $password, $_SERVER['site_key']); 

to store and encrypt the password into database on registration.

For login: I need to compare password, how do I do that ?


Here's my full code:

<?php

    session_start();

    $mysqli = mysqli_connect("localhost", "", "", "");

    $error = ""; //Variable for storing our errors.

    if(isset($_POST["submit"])){

    if(empty($_POST["emailadd"]) || empty($_POST["password"])){
    $error = "Both fields are required.";
    }
    else {
    // Define $emailadd and $password
    $emailadd=$_POST['emailadd'];
    $password=$_POST['password'];

    // To protect from MySQL injection
    $emailadd = stripslashes($emailadd);
    $password = stripslashes($password);
    $emailadd = mysqli_real_escape_string($mysqli, $emailadd);
    $password = mysqli_real_escape_string($mysqli, $password);
    $password = hash_hmac('sha512', 'salt' . $password, $_SERVER['site_key']);

    //Check username and password from database

    $sql="SELECT * FROM member WHERE emailadd='$emailadd'";
    $result=mysqli_query($mysqli,$sql);
    $row=mysqli_fetch_array($result,MYSQLI_ASSOC);

    //If username and password exist in our database then create a session.
    //Otherwise echo error.

    if(mysqli_num_rows($result) == 1 and $password == hash_hmac('sha512', 'salt' . $_REQUEST['password'], $_SERVER['site_key'] )){
    $_SESSION['emailadd'] = $login_user; // Initializing Session
    header("location: pages/dashboard.html"); // Redirecting To Other Page
    }else{
    $error = "Incorrect email address or password.";
    }

    }
    } 

?>

I just can't seem to get it right, could someone advice me please,Thanks

回答1:

Just hash the password the user types in when they login the same way you hash it when they register, then get the encrypted password from the database and compare them

$hashPass=hash_hmac('sha512', 'salt' . $password, $_SERVER['site_key']);
$query='SELECT password FROM yourtablename WHERE user=$user';
$getPass1=mysqli_query($link, $query);
$getPass2=mysqli_fetch_row($getPass1);
$getPass=$getPass2[0];
if($hashPass==$getPass){
    // yay password is right
};


标签: php mysqli