当我使用MD5函数作为密码时,由于连接不成功,因此不会向数据库添加任何内容。为什么是这样?

时间:2017-08-22 14:21:09

标签: php mysql

为什么当“$ password = md5($ password)”没有被注释掉时,插入查询不成功?

if (isset($_POST['signupFootball'])) {

    $firstname = mysqli_real_escape_string($con, $_POST['fname']);
    $lastname = mysqli_real_escape_string($con, $_POST['lname']);
    $email = mysqli_real_escape_string($con, $_POST['email']);
    $password = $_POST['password'];

    $password = md5($password);

    if (mysqli_query($con,"INSERT into `users`(fname, lname, email, password) VALUES ('$firstname', '$lastname', '$email', '$password')")) {
        echo "<h1><strong>successful connection</strong></h1>";

        $_SESSION['fname'] = $firstname;
        $_SESSION['success'] = 'You have been registered successfully';

        header('location: signupcomplete.php');
    }
    else {
        echo "<h1><strong>unsuccessful connection</strong></h1>";
        echo "<a href=\"index.php\">Go back home</a>";
    }
}

1 个答案:

答案 0 :(得分:2)

<强> STOP!

FORGET md5 ...

PHP有一个password_hash()功能,它很漂亮..

  1. 您的列必须为VARCHAR(255)
  2. 这是单向哈希并且非常安全。在插入db ...

    之前执行此操作
    $passwordFromUser = $_POST['password'];
    $passwordToInsert = password_hash($passwordFromUser, PASSWORD_DEFAULT);
    
    //no need for mysql_real_escape_string
    //do the above and your password troubles are over
    

    要验证密码,请将其从数据库中取出并执行以下操作:

    $passwordFromUser = $_POST['password'];
    $passwordFromDB = //however you get this out of the database..
    
    if (password_verify($passwordFromUser, $passwordFromDB){
         echo 'Good!';
    }
    else{
        echo 'bad';
    }
    

    附注:我认为PDO是一种处理数据库的更简洁的方法..