How do I encrypt this password with MD5 using PHP?

本秂侑毒 提交于 2019-12-06 16:13:33

问题


The code below is from a login script, written in PHP. The database that it checks passwords against encrypts the passwords using MD5 however when the login script checks against the database for a password, it is checking the raw password without encryption. I am familiar with the md5() function but how would I incorporate that into the following:

<?php
session_start();

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

if ($username && $password) {
    $connect = mysql_connect("host", "user", "password") or die("Couldn't connect");
    mysql_select_db("dbname") or die("Couldn't find the database");

    $query = mysql_query("SELECT * FROM users WHERE username='$username'");
    $numrows = mysql_num_rows($query);

    if ($numrows != 0) {
        while ($row = mysql_fetch_assoc($query)) {
            $dbusername = $row['username'];
            $dbpassword = $row['password'];
        }

        if ($username == $dbusername && $password == $dbpassword) {
            echo "You're in! Click <a href='../member.php'>here</a> to enter the member page.";
            $_SESSION['username'] = $username;
        }else{
            echo "Incorrect password";
        }
    }else{
        die("That username does not exist.");
    }
}else{
    die("Please enter a valid username and password.");
}
?>

回答1:


You should be checking and querying the database for a match, not bringing the results down and checking them locally. With that said:

$password = md5($_POST['password']);

Then also change:

SELECT * FROM users WHERE username='$username' AND password='$password'

But I'd also have a look at using PDO instead of placing the values directly in a SQL query. At the very least you should be using mysql_real_escape_string to avoid injection attacks.




回答2:


    $salt=sha1($postpassword);
    $arr= strlen($postpassword);
    $count=ceil($arr/2);
    $stringarr=str_split($postpassword,$count);
    $password1=hash("sha512", $stringarr['0']); 

    $password2=$salt . ( hash( 'whirlpool', $salt . $stringarr['1'] ) );
    return $password1.$password2;


来源:https://stackoverflow.com/questions/12666212/how-do-i-encrypt-this-password-with-md5-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!