2016-02-04 34 views
0

我試圖做一個登錄腳本,但它似乎沒有正確地從我的數據庫中讀取密碼,我不知道爲什麼。登錄腳本沒有正確讀取密碼?

這是我的PHP代碼:

<? 

if ($_POST['login'] == "login") { 
    include('db.php'); 
    include('inc/scriptsandstyles.php'); 
    include('inc/passwordLib.php'); 

    $username = (isset($_POST['username'])? $_POST['username'] : null); 
    $password = (isset($_POST['password'])? $_POST['password'] : null); 

    $res = mysqli_query($conn, "SELECT user_name, user_password FROM rgitportal_users WHERE user_name='$username'"); 

    $row = mysqli_fetch_array($res); 

    $pw_hash = $row['user_password']; 

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

     echo '<script type="text/javascript">window.location = "http://rgitportal.com/home.html"</script>'; 

} else { 
    $errormsg = "Username or password incorrect"; 
} 

} 
?> 

這是password_verify函數的聲明方式(運行PHP版本5.3),並且是包含在登錄腳本passwordLib.php內。

if (!function_exists('password_verify')){ 
function password_verify($password, $hash){ 
    return (crypt($password, $hash) === $hash); 
    } 
} 

這就是表單代碼:

<form id="login_form" name ="login" id ="login" action ="index.php" method = "POST"> 
    <div class ="field_container"> 
     Username: <input type="text" name ="username" id ="username"></input> 
      </div> 
    <div class ="field_container"> 
     Password: <input type="password" name ="password" id ="password"></input> 
      </div> 
    <div class ="field_container"> 
     <input type="submit" value="login" name ="login" id="login"></input> 
      </div> 
    <span style="color:#FF0000;"><?=$errormsg?></span> 
</form> 

如果我輸入用戶名和密碼正確它總是落在我的if語句的else,檢查密碼。變量正在從表單和有問題的數據庫中正確分配。數據庫中保存密碼的文本字段被存儲爲密碼,因此被加密。

我在做什麼錯?

+0

「在數據庫中的文本字段持有密碼存儲爲密碼,因此被加密「。你正在使用數據庫的PASSWORD功能嗎? –

回答

0

我認爲crypt()的第二個參數不應該是$ hash。當您在數據庫中創建並存儲密碼時,您使用了什麼鹽?

1

也許這將有所幫助:http://php.net/manual/en/function.crypt.php

第一個例子是展示,您應該驗證使用hash_equals($ hashed_pa​​ssword,隱窩($ USER_PASSWORD [,$ optional_salt))。

(對於年齡較大的PHP版本,從http://php.net/manual/en/function.hash-equals.php截取):

<?php 
if(!function_exists('hash_equals')) { 
    function hash_equals($str1, $str2) { 
    if(strlen($str1) != strlen($str2)) { 
     return false; 
    } else { 
     $res = $str1^$str2; 
     $ret = 0; 
     for($i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]); 
     return !$ret; 
    } 
    } 
} 
?> 

請記住,即隱窩使用鹽作爲第二個參數,而不是散列密碼。

希望這會有所幫助。

-1

嘗試使你的代碼更改如下:

主代碼

if (password_verify($password, $pw_hash)) 
{ 
    header('Location:http://rgitportal.com/home.html'); 
} else 
{ 
    $errormsg = "Username or password incorrect"; 
} 

passwordLib.php

if (!function_exists('password_verify')) 
{ 
    function password_verify($password, $hash) 
    { 
     return (crypt($password) === $hash); 
    } 
}