2017-09-15 116 views
-2

你好,我嘗試使用pdo從數據庫返回散列密碼,並允許用戶登錄,而他們的密碼被保護。我已經建立了一個註冊頁面,其中輸入密碼。我現在試圖去解決這個問題。我認爲我很接近,但這已經有很多日子停留在同一個地方,我希望有人能幫我完成我的代碼?試圖驗證散列密碼和驗證登錄pdo php

PHP致命錯誤:未捕獲錯誤:調用成員函數fetch()布爾值在/var/www/html/login.php:54\nStack trace:\ n#0 {main} \ n拋出/無功/ www/html等/ login.php中上線54,引用者:http://172.16.62.211/login.php

if (isset($_POST['submit'])){ 
    $username = $_POST['username']; 
    $password = $_POST['password']; 

    $q = $handler->prepare('SELECT * FROM users WHERE username = ?'); 
    $query = $q->execute(array(
     $username)); 
    $_SESSION['username'] = $username; 
    $count = $q->rowCount(); 
    if ($count == 1 -> fetch(PDO::FETCH_ASSOC)){ 
     $hash_pwd = $count['password']; 
     $hash = password_verify($password, $hash_pwd); 

    if ($hash_pwd == 0) { 
     header("location: login.php?error=empty"); 
    } 

    else { 
    $q = $handler->prepare('SELECT * FROM users WHERE username = ? && password = $hash_pwd'); 
    $query = $q->execute(array(
     $username, 
     $password)); 

    $count = $q->rowCount(); 
     if($count == 1){ 
      $_SESSION['username'] = $username; 
      header("location: index.php"); 
      return; 
     } else { 
     echo '<p class="error-message3">'.'<br>'.'<br>'."You have ented an incorrecct login!<br>Please try again.".'</p>'; 
    }}}} 
    ?> 
+0

*「我現在正試圖去解決這個問題。」* - 你究竟是什麼意思?哪一條是第54行? –

+0

您也只在查詢中有1個佔位符,但在數組中使用2作爲'$ q = $ handler-> prepare('SELECT * FROM users WHERE username =?&& password = $ hash_pwd');'。這也是失敗的另一個原因。 –

+0

@ Fred-ii-我試圖在我的數據庫中散列一個哈希密碼來啓用登錄。 –

回答

0

你不會和你不能 'dehash' 的從你的數據庫密碼。

正常程序基本上由of converting the password inserted by the user to your security logic encrypt and compare with the password stored in your db (hashed too)組成,這兩個值必須等於驗證。

Dehash的密碼是,如果哈希正確完成,在某些方面是不可能的,而不是指出你的想法的安全漏洞。

if ($count == 1 -> fetch(PDO::FETCH_ASSOC)){ 
     $hash_pwd = $count['password']; 
     $hash = password_verify($password, $hash_pwd); 
     if ($hash === false) { 
      header("location: login.php?error=empty"); 
     } else { 

       $_SESSION['username'] = $username; 
       header("location: index.php"); 
       return; 
      } 
    } else { 
      echo '<p class="error-message3">'.'<br>'.'<br>'."You have ented an incorrecct login!<br>Please try again.".'</p>'; 
     } 

PS:縮進更好的代碼,並指出了一些程序,你正在重複檢查,你已經籤像上面說的password_verify。

+0

好吧,夥計們,抱歉,我明白我無法排除,但是如何驗證密碼? –

+0

你看看'password_verify()'是否返回了真@diced。菠蘿 –

+0

我已經在問題中說過:您在登錄時轉換用戶插入的密碼並在您的數據庫中進行比較 – calexandre

0

您需要了解的password_verify使用,它需要(非散列)密碼的版本和散列版本(從數據庫),並分別返回真/假。

<?php 
if (password_verify($raw, $hash)) { 

} 
?> 

你並不需要在你的查詢比較,剛剛從所提供的用戶名(如果用戶名是有效的),然後驗證找回密碼。

+0

向下選民,謹慎解釋?如果我的回答有問題,請說。不要只是投票和離開。 – Script47