2017-02-10 9 views
0

здесь является register.inc.php password_verify() в PHP возвращает ложь для правильного пароля

<?php 
 
include_once 'db_connect.php'; 
 
include_once 'psl-config.php'; 
 
include_once 'functions.php'; 
 
$error_msg = ""; 
 

 
sec_session_start(); 
 

 
    if (isset($_POST['username'], $_POST['email'], $_POST['p'], $_POST['firstname'], $_POST['lastname'], $_POST['email'], $_POST['contactno'], $_POST['address'], $_POST['inviteid'] 
 
    )) { 
 
    // Sanitize and validate the data passed in 
 
    $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING); 
 
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); 
 
    $email = filter_var($email, FILTER_VALIDATE_EMAIL); 
 
    $phone = filter_input(INPUT_POST,'contactno', FILTER_SANITIZE_STRING); 
 
    $firstname = filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING); 
 
    $lastname = filter_input(INPUT_POST, 'lastname', FILTER_SANITIZE_STRING); 
 
    $inviteid = filter_input(INPUT_POST, 'inviteid', FILTER_SANITIZE_STRING); 
 
    $address = filter_input(INPUT_POST, 'address', FILTER_SANITIZE_STRING); 
 
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
 
     // Not a valid email 
 
     $error_msg .= '<p class="error" style="color:red; font-size:16px;>* The email address you entered is not valid</p>'; 
 
    } 
 
    
 
    $password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING); 
 
    if (strlen($password) != 128) { 
 
     // The hashed pwd should be 128 characters long. 
 
     // If it's not, something really odd has happened 
 
     $error_msg .= '<p class="error" style="color:red; font-size:16px;>* Invalid password configuration.</p>'; 
 
    } 
 

 
    
 
    // Username validity and password validity have been checked client side. 
 
    // This should should be adequate as nobody gains any advantage from 
 
    // breaking these rules. 
 
    // 
 
    
 
    $prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1"; 
 
    $stmt = $mysqli->prepare($prep_stmt); 
 
    
 
    // check existing email 
 
    if ($stmt) { 
 
     $stmt->bind_param('s', $email); 
 
     $stmt->execute(); 
 
     $stmt->store_result(); 
 
    
 
     if ($stmt->num_rows == 1) { 
 
      // A user with this email address already exists 
 
      $error_msg .= '<p class="error" style="color:red; font-size:16px;">* A user with this email address already exists.</p>'; 
 
         $stmt->close(); 
 
     } 
 
    } else { 
 
     $error_msg .= '<p class="error" style="color:red; font-size:16px;>* Database error Line 39</p>'; 
 
       $stmt->close(); 
 
    } 
 
    
 
    // check existing username 
 
    $prep_stmt = "SELECT id FROM members WHERE username = ? LIMIT 1"; 
 
    $stmt = $mysqli->prepare($prep_stmt); 
 
    
 
    if ($stmt) { 
 
     $stmt->bind_param('s', $username); 
 
     $stmt->execute(); 
 
     $stmt->store_result(); 
 
    
 
       if ($stmt->num_rows == 1) { 
 
         // A user with this username already exists 
 
         $error_msg .= '<p class="error" style="color:red; font-size:16px;">* A user with this username already exists</p>'; 
 
         $stmt->close(); 
 
       } 
 
    } else { 
 
     $error_msg .= '<p class="error" style="color:red; font-size:16px;>* Database error line 55</p>'; 
 
     $stmt->close(); 
 
    } 
 

 
    // check existing username 
 
    $prep_stmt = "SELECT id FROM members WHERE myid = ? LIMIT 1"; 
 
    $stmt = $mysqli->prepare($prep_stmt); 
 
    
 
    if ($stmt) { 
 
     $stmt->bind_param('s',$_POST['inviteid']); 
 
     $stmt->execute(); 
 
     $stmt->store_result(); 
 
    
 
       if ($stmt->num_rows == 0) { 
 
         // A user with this us 
 
         $error_msg .= '<p class="error" style="color:red; font-size:16px;">* No user with this id exists</p>'; 
 
         $stmt->close(); 
 
       } 
 
    } else { 
 
     $error_msg .= '<p class="error" style="color:red; font-size:16px;>* Database error line 55</p>'; 
 
     $stmt->close(); 
 
    } 
 
       //1.86€y9.31€$Ac2w6xufmG.jI3F/5GZhDOdW1TzAPrnJ3oPF0seGHI6g03QopB4C 
 

 
     // TODO: 
 
     // We'll also have to account for the situation where the user doesn't have 
 
     // rights to do registration, by checking what type of user is attempting to 
 
     // perform the operation. 
 
     
 
     if (empty($error_msg)) { 
 
      // Create hashed password using the password_hash function. 
 
      // This function salts it with a random salt and can be verified with 
 
      // the password_verify function. 
 

 
      $passwords = password_hash($password,PASSWORD_BCRYPT); 
 
     
 
      // Insert the new user into the database 
 
      if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password,firstname,lastname,phone,address,inviteid) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")) { 
 
       $insert_stmt->bind_param('ssssssss', $username, $email, $passwords, $firstname, $lastname, $phone, $address, $inviteid); 
 
       // Execute the prepared query. 
 
       if (! $insert_stmt->execute()) { 
 
        header('Location: ../error.php?err=Registration failure: INSERT'); 
 
       } 
 
      } 
 
      /*if (login($_POST['email'],$_POST['p'], $mysqli) == true) { 
 
        // Login success 
 
        header('Location: dashboard.php'); 
 
       }else{ 
 
        // Login failed 
 
        //header('Location: login.php'); 
 
       } */ 
 
      // header('Location: dashboard.php'); 
 
      //exit(); 
 
     } 
 
} 
 

 
?>

process_login.php

<?php 
 
include_once 'db_connect.php'; 
 
include_once 'functions.php'; 
 
include_once '../securimage/securimage.php'; 
 

 
//$securimage = new Securimage(); 
 
sec_session_start(); // Our custom secure way of starting a PHP session. 
 
    
 
if (isset($_POST['email'], $_POST['p'])) { 
 
    $email = $_POST['email']; 
 
    $password = $_POST['p']; // The hashed password. 
 

 
     if (login($email, $password, $mysqli) == true) { 
 
      // Login success 
 
      //  header("Location: ../protected_page.php"); 
 
      header('Location: ../dashboard.php'); 
 
     }else{ 
 
      // Login failed 
 
      header('Location: ../login.php?error=1'); 
 
     }  
 

 
} else { 
 
    // The correct POST variables were not sent to this page. 
 
    header('Location: ../error.php?err=Could not process login'); 
 
    exit(); 
 
}

Привет там Я пытаюсь хэш мои пароли с password_hash() в PHP. Эта часть прекрасно, но для сравнения хэш возвращает ложь, несмотря ни на что. Чтобы войти в систему, я проверяю базу данных учетной записи пользователя и захватываю хэш-код пароля, а затем сравниваю его с введенным паролем. Здесь были проверены все решения. Мой код выглядит следующим образом:

function login($email, $password, $mysqli) { 
    // Using prepared statements means that SQL injection is not possible. 
    if ($stmt = $mysqli->prepare("SELECT id, username, password, myid, firstname, lastname,status,ambLevel 
     FROM members 
     WHERE email = ? 
     LIMIT 1")) { 
     $stmt->bind_param('s', $email); // Bind "$email" to parameter. 
     $stmt->execute(); // Execute the prepared query. 
     $stmt->store_result(); 


     // get variables from result. 
     $stmt->bind_result($user_id, $username, $db_password, $myid, $fname, $lname, $status, 
      $ambLevel); 
     $stmt->fetch(); 

     var_dump($db_password); 
     var_dump($password); 

     if ($stmt->num_rows == 1) { 
      // If the user exists we check if the account is locked 
      // from too many login attempts 

      if (checkbrute($user_id, $mysqli) == true) { 
       // Account is locked 
       // Send an email to user saying their account is locked 
       return false; 
      } else { 
       // Check if the password in the database matches 
       // the password the user submitted. We are using 
       // the password_verify function to avoid timing attacks. 
       if (password_verify($password,$db_password)) { 
        // Password is correct! 
        // Get the user-agent string of the user. 
        $user_browser = $_SERVER['HTTP_USER_AGENT']; 
        // XSS protection as we might print this value 
        $user_id = preg_replace("/[^0-9]+/", "", $user_id); 
        $_SESSION['user_id'] = $user_id; 
        // XSS protection as we might print this value 

        $username = preg_replace("/[^a-zA-Z0-9_\-]+/", 
                   "", 
                   $username); 
        $_SESSION['username'] = $username; 
        $_SESSION['firstname'] = $fname; 
        $_SESSION['lastname'] = $lname; 
        $_SESSION['myid'] = $myid; 
        $_SESSION['email'] = $email; 
        $_SESSION['status'] = $status; 
        $_SESSION['ambLevel'] = $ambLevel; 
        $_SESSION['login_string'] = hash('sha512', 
           $db_password . $user_browser); 
        // Login successful. 
        return true; 
       } else { 
        // Password is not correct 
        // We record this attempt in the database 
        $now = time(); 
        $mysqli->query("INSERT INTO login_attempts(user_id, time) 
            VALUES ('$user_id', '$now')"); 
        return false; 
       } 
      } 
     } else { 
      // No user exists. 
      return false; 
     } 
    } 
} 

Просьба помочь. Весь мой исходный код here.

+0

Это должно сработать. Просто попробуйте с некоторыми фиктивными значениями. –

+0

Его действие не работает с правильным паролем. –

+0

Второй параметр 'verify_password' должен быть' hash', не так ли? [password_verify()] (http://php.net/manual/en/function.password-verify.php) – Mohammad

ответ

0

Работы, как ожидается, ...

<?php 

$hash=password_hash("password", PASSWORD_DEFAULT); 
if (password_verify("password", $hash)) { 
    echo 'Password is valid!'; 
} else { 
    echo 'Invalid password.'; 
} 
?> 
0

У меня была такая же проблема, и решить ее, установив столбец паролей в моей БД на достаточно длинной (255) VARCHAR вместо CHAR или переменной NCHAR , Если это не помогает, попробуйте var_dump во всех точках передачи: при первом хешировании, взятии его из самой базы данных и после отправки запроса.