我有一个非常简单的登录/用户注册脚本,使用sha1和salt存储密码.我有密码和用户创建工作正常,并将所有内容存储在数据库中,但是当我尝试使用凭据登录时,它不起作用.在搜索这个主题时,我似乎找不到任何东西.
session_start(); include("includes/resume.config.PHP"); // make sure form fields have a value and strip them function check_input($data,$problem='') { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); if ($problem && strlen($data) == 0) { die($problem); } return $data; } // get form values,escape them and apply the check_input function $name = $link->real_escape_string(check_input($_POST['name'],"Please enter a name!")); $email = $link->real_escape_string(check_input($_POST['email'],"Please enter an email!")); $password = $link->real_escape_string(check_input($_POST['password'],"Please enter a password!")); // generate a random salt for converting passwords into MD5 $salt = bin2hex(mcrypt_create_iv(32,MCRYPT_DEV_URANDOM)); $saltedPW = $password . $salt; $hashedPW = sha1($saltedPW); MysqLi_connect($db_host,$db_user,$db_pass) OR DIE (MysqLi_error()); // select the db MysqLi_select_db ($link,$db_name) OR DIE ("Unable to select db".MysqLi_error($db_name)); // our sql query $sql = "INSERT INTO admins (name,email,password,salt) VALUES ('$name','$email','$hashedPW','$salt');"; //save the updated information to the database MysqLi_query($link,$sql) or die("Error in Query: " . MysqLi_error($link)); if (!MysqLi_error($link)) { header("Location: file_insert.PHP"); }
这是我的登录脚本:这是不起作用的
function check_input($data,$problem='') { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); if ($problem && strlen($data) == 0) { die($problem); } return $data; } if(isset($_POST['submitLogin'])) { //form submitted? // get form values,"Please enter a name!")); $password = $link->real_escape_string(check_input($_POST['password'],"Please enter a password!")); $saltQuery = $link->query('SELECT salt FROM admins WHERE name = "'.$name.'"'); $salt = MysqLi_fetch_assoc($saltQuery); $saltedPW = $password . $salt; $hashedPW = sha1($saltedPW); MysqLi_connect($db_host,$db_name) OR DIE ("Unable to select db".MysqLi_error($db_name)); $validate_user = $link->query('SELECT id,name,password FROM admins WHERE name = "'.$name.'" AND password = "'.$hashedPW.'"'); if ($validate_user->num_rows == 1) { $row = $validate_user->fetch_assoc(); $_SESSION['id'] = $row['id']; $_SESSION['loggedin'] = TRUE; Header('Location: file_insert.PHP'); } else { print "<center><p style='margin-top: 200px; font-weight: bold;'>Invalid Login information</p>"; print "<a href='admin-login.PHP'>Click here</a> to return to the login page.</center>"; } }
解决方法
可能会有更多的事情发生,但肯定的一个原因是它不起作用是因为
mysqli_fetch_assoc
返回一个数组,而你正在使用它像一个字符串.
当你调用$password时,PHP会抱怨数组转换为字符串. $salt因为此时$salt是一个数组.结果是您在密码后面附加了单词Array,导致散列不正确.如果您关闭了display_errors和/或将error_reporting设置为隐藏PHP.ini中的通知,那么您将看不到此消息.
如果你改变:
$saltedPW = $password . $salt;
至:
$saltedPW = $password . $salt['salt'];
那它应该工作.
此外,您应该在将$插入数据库之前转义$salt,因为它可能包含null,unprintable或单/双引号,因为它是随机生成的.