我试图让我的新登录系统工作,我创建了一个简单的密码并使用下一个代码将散列传递到我的MySQL表
makepass.php
<?php
$password = "testpass";
$hash = password_hash($password, PASSWORD_DEFAULT);
echo $hash;
?>
dologin.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('includes/functions.php');
session_start();
if(isset($_POST['login'])) {
if(isset($_POST['username'])) {
if(isset($_POST['password'])) {
$username = $_POST['username'];
$dbconn = mysqli_query($query, "SELECT * FROM cm_users WHERE Username = '$username'") or die(mysqli_error($query));
foreach ($dbconn as $user) {
if (password_verify($_POST['password'], $user['Password'])) {
$_SESSION['user'] = $user['Username'];
} else {
echo 'Invalid password!';
}
}
} else {
echo 'Invalid username!';
}
}
}
?>
所以我尝试使用“testpass”和whoala:无效密码登录!
有什么想法吗? Afaik它应该没问题,我没有看到任何语法或其他问题。
答案 0 :(得分:4)
你不应该成为foreach
,但首先要查询,获取数组(你没有使用),然后将其与行的密码。
旁注:用您自己的凭据替换("xxx", "xxx", "xxx", "xxx")
。但是,使用$query
并不是一个应该用作连接变量的单词,因为它非常混乱。
(甚至在写我的答案时我很困惑)。使用$connection
或$conn
我已经在此处进行了更改,因此请改用它。
$conn = new mysqli("xxx", "xxx", "xxx", "xxx");
if ($conn->connect_error) {
die('Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
if(isset($_POST['login'])) {
$username = $_POST['username']; // you could use a conditional !empty() here
$password = $_POST['password']; // here also
$query = "SELECT * FROM cm_users WHERE Username = '".$conn->real_escape_string($username)."';";
$result = $conn->query($query);
// error checking on the query
if (!$result) {
echo "<p>There was an error in query: $query</p>";
echo $conn->error;
}
$row_hash = $result->fetch_array();
if (password_verify($password, $row_hash['Password'])) {
echo "Welcome!";
}
else{
echo "Invalid";
}
}
旁注:确保您的POST数组确实包含值并且不包含空格。如果有,请使用trim()
。
即:
$username = trim($_POST['username']);
$password = trim($_POST['password']);
同时检查查询错误:
错误报告:
答案 1 :(得分:0)
$dbconn = mysqli_query($query, "SELECT * FROM cm_users WHERE Username = '$username'") or die(mysqli_error($query));
看起来应该更像
$userQuery = mysqli_query($variableToConnectToDatabase, "SELECT * FROM cm_users WHERE Username = '$username' AND Password='$password' LIMIT 1 ")
不确定您的主要目标是什么。您是否希望用户能够输入自己的密码,或者密码是否应该保持不变?
答案 2 :(得分:0)
尝试编辑dologin.php到此.....
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('includes/functions.php');
if(isset($_POST['login'])) {
if(isset($_POST['username'])) {
if(isset($_POST['password'])) {
$username = $_POST['username'];
$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
$dbconn = mysqli_query($query, "SELECT * FROM cm_users WHERE Username = '$username'") or die(mysqli_error($query));
foreach ($dbconn as $user) {
if ($hash == $user['Password']) {
$_SESSION['user'] = $user['Username'];
} else {
echo 'Invalid password!';
}
}
} else {
echo 'Invalid username!';
}
}
}
?>