iT邦幫忙

1

PHP password verify (hash)的問題 [已解決]

不明 2022-07-10 09:12:491089 瀏覽
  • 分享至 

  • xImage

login_login.php是我用來驗證資料庫裏面 加密後密碼的login form

驗證沒有hash的密碼是正常成功的

但驗證hash後的密碼會顯示Invalid (不相符)?

請問為什麼驗證不了hash過的密碼呢?

已排除輸入錯誤 因為都是用一個字的 username (a) , password (1) 去測試

login_login.php

<?php
if(isset($_POST['login'])){
    $connection = mysqli_connect('localhost','root','','loginapp');

    if(!$connection){
        die("FAILED to Connect to Database ! ");
    }

    $uname = $_POST['username'];
    $pwd = $_POST['password'];


    $query = "SELECT * ";
    $query .= "FROM users ";
    $query .= "WHERE username = '". $uname ."'";

    $result = mysqli_query($connection,$query);

    if(!$result){
        die('QUERY FAILED ! '.mysqli_error($connection));
    }


    $rows = mysqli_fetch_assoc($result);

    $passwordHash = $rows['password'];

    /*

    
    if($pwd == $rows['password']){
        echo "WELCOME !";
    }else{
        echo "Invalid";
    }

  */

    echo $pwd;  //testing

    echo $passwordHash; //testing


        if(password_verify($pwd, $passwordHash)){
            echo "Welcome ! ".$rows['$username'];
        }else{
            echo "Invalid";
        }
    
    
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <form action="login_login.php" method="post">
        <label for="username">USERNAME</label>
        <input type="text" name="username">
        <br>
        <label for="password">PASSWORD</label>
        <input type="password" name="password">
        <br>
        <input type="submit" name="login" value="LOGIN">
    </form>
</body>
</html>

create user 的 function

login_create.php


include "db.php";

function createRow(){
    global $connection; 
    if(isset($_POST['submit'])){
        $uname = $_POST['username'];
        $password = $_POST['pwd'];
    
        $uname = mysqli_real_escape_string($connection, $uname);
        $password = mysqli_real_escape_string($connection, $password);

        //password encryption
        $password = password_hash($password, PASSWORD_DEFAULT);


    
        $query = "INSERT INTO users(username,password) VALUES ('$uname','$password');";
    
    
        $result = mysqli_query($connection,$query);
    
        if(!$result){
            die('Query FAILED' . mysqli_error($connection));  
        }else{
            echo "Record Create";
        }
    }
}

phpmyAdmin

database : loginapp
table : users
row : id (int) , username (var 255), password (var 255)

不明 檢舉
原來是database datatype的長度問題
一開始 我的password datatype長度設定了 (var 32)
後面才改成(var 255) 然後重新創建一個使用者 就成功了!
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答