【发布时间】:2017-10-25 01:39:56
【问题描述】:
我有一个我正在尝试解决的项目的登录名。我已经通过 POST(通过 AJAX 调用)获得了一个值,我已经检查了输入的用户名是否存在并且直到那里,它运行良好。但是知道我想检查密码是否对该用户名有效。这是 PHP 代码:
<?php
//File with the conection data
include_once "../conexion.php";
//Initialization
$user = "";
$password = "";
$errors = "";
$result = "";
$result2 = "";
//Some validations (I've edited a little to make it shorter)
if((isset($_POST['user'])) && (!empty($_POST['user']))){
$user = $_POST['user'];
}else{
$errors .= "blablablah";
}
if((isset($_POST['password'])) && (!empty($_POST['password']))){
$password = $_POST['password'];
}else{
$errors .= "blablabla";
}
//I make the query
$sql = "SELECT user FROM users WHERE user = ?";
//I prepare the query
if($stmt = $con->prepare($sql)){
$stmt->bind_param('s', $user);
$result = $stmt->execute();
}
/* UP TO HERE, if I check that $result is true and echo "User exists" or something like that, IT WORKS, AS THE USER EXISTS */
/* BUT now I want to check the PASSWORD, given that the user exists */
if($result){
//I make the query
$sql2 = "SELECT user, password FROM users WHERE user = ? AND password = ?";
//I prepare the query
if($stmt2 = $con->prepare($sql2)){
$stmt2->bind_param('ss', $user, $password);
$result2 = $stmt2->execute();
if($result2){
echo "ENTERED";
}else{
echo "PASSWORD OR USER INCORRECT";
}
}
}
?>
我在 AJAX 调用的成功函数中使用了这些回显的结果,这是该代码(在表单的按钮中有一个 onClick 事件 (onClick="login()"),validationLogin( ) 具有字段的所有验证 --> 一切正常):
function login(){
if(validationLogin()){
$.ajax({
url: "http://localhost/myProject/extras/Login.php",
type: "POST",
data: {"user": user,
"password": password,
},
dataType: "html",
cache: false,
beforeSend: function() {
console.log("Processing...");
},
success:
function(data){
alert(data);
console.log(data);
}
});
}else{
//alert("Incorrect fields");
}
}
这返回 EMPTY,我提醒数据只是为了检查它有什么...提醒是空的,不明白为什么:/
我已经尝试过这个想法 --> PHP mySQL check if username and password are in the database 但在这种情况下它一直说它不正确:/
几点说明:
- 我知道密码应该加密,以后可能会使用md5。
- 通过使用 PHP 文件中的 echos 和 JS 文件中的 alert(data) / console.log(data),我只想检查 是否有效,以便继续。也许还有其他方法,更好的方法来做这一切,我知道,但我喜欢一点一点地进行
- 我真的很想理解我的代码,然后会改进它,我真的很想了解它的功能和原因
- 我想继续使用准备好的语句
提前感谢大家! :)
【问题讨论】:
-
从不存储纯文本密码。您应该改用
password_hash()和password_verify()。如果您使用的是 5.5 之前的 PHP 版本,请不要使用 MD5 或 SHA1 来散列密码。相反,您可以使用this compatibility pack。 -
@AlexHowansky 感谢您的提醒,我已经在帖子末尾提到了一些相关内容。
-
“我已经尝试过这个想法 --> PHP mySQL 检查用户名和密码是否在数据库中,但在这种情况下它一直说它不正确” - 我'那里有一个公认的答案(可以追溯到 2014 年),所以无论 OP 的问题的代码/答案之间存在什么差异,其他的东西都会让你失望。
-
如果要检查行是否存在,使用
num_rows,并绑定结果;并检查错误;你没有那样做。这就是你发布失败的原因。 -
您不需要两个查询。进行一次查询以获取该行。如果它没有返回任何内容或密码匹配失败,则返回一般错误。尽量避免暴露不存在的用户和不正确的密码之间的区别。