Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

php - Comparing/check if correct Password from mysqli database [hash_hmac]

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...