所以我有一个名为register.php的文件和一个名为login.php的文件,两者都使用
passwordhash($pasw, DEFAULT_PASSWORD)
,register.php创建哈希并将其放入数据库,login.php查看用户输入的密码哈希是否与数据库条目匹配。
register.php:
/*db info above */
$conn = new mysqli($servername, $username, $password, $dbname);
$user = $_POST['user'];
$pasw = $_POST['pasw'];
if($user !== mysqli_real_escape_string($conn, $user) || ctype_alnum($user) !== true) {
$_SESSION['errormsg'] .= "<script>alert('Invalid Username, Must be alphanumerical')</script>";
$error = 1;
}
if(strlen($pasw) >= 16 || strlen($pasw) < 4) {
$_SESSION['errormsg'] .= "<script>alert('Invalid Username, must be more than 4 and less than 16 characters long')</script>";
$error = 1;
}
if(strlen($pasw) < 8 ) {
$_SESSION['errormsg'] .= "<script>alert('Invalid Password, Must be AT LEAST 8 characters')</script>";
$error = 1;
}
if($error === 1) {
Header('Location: index.php');
exit();
}
$pasw = password_hash($pasw, PASSWORD_DEFAULT);
$curtime = time();
$userip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO userdata (user, password, timestamp, IP) values ('$user', '$pasw', '$curtime', '$userip')";
if (mysqli_query($conn, $sql)){
$_SESSION['name'] = $user;
if($user === 'Admin') {
$_SESSION['admin'] = 'yes';
}
Header('Location: index.php');
exit();
}
else {
$_SESSION['errormsg'] = "<script>alert('Unknown Error')</script>";
Header('Location: index.php');
}
和login.php:
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = mysqli_real_escape_string($conn, $_POST['user']);
$pasw = $_POST['pasw'];
$paswhash = password_hash($_POST['pasw'], PASSWORD_DEFAULT);
$result = mysqli_query($conn, "SELECT * FROM userdata where user = '$name' and password = '$paswhash'");
var_dump($result);
if(mysqli_num_rows($result) > 0) {
$_SESSION['name'] = $name;
Header('Location: index.php');
}
else {
$_SESSION['errormsg'] = "<script>alert('Invalid user/pass combo" . $name . " " . $paswhash . "')</script>";
//displaying name and password hash for debugging reasons
Header('Location: index.php');
}
来自register.php的数据很好地写入数据库,但是当我在输入字段中输入未散列的密码时,它们不匹配,并且错误消息指出密码成为另一个散列。
我做的事情非常糟糕吗?