我正忙着使用PHP / MySQL登录系统,只是为了好玩。 我做了这个功能:
function login($username, $password) {
$user_id = user_id_from_username($username);
$password = md5($password);
return (mysql_result(mysql_query("SELECT COUNT (`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'"), 0) == 1) ? $user_id : false;
但由于某种原因它总是返回user_id,永远不会假,即使登录凭据错误!
答案 0 :(得分:1)
function login($username, $password) {
//$user_id = user_id_from_username($username); // remove this line down to the if statement
$password = md5($password);
$query = mysql_query("SELECT `username`, `password` FROM `users` WHERE `username` = '$username' AND `password` = '$password'");
// Check if the query was a success
if($query) {
// Check if there is a user with the matching data
if(mysql_num_rows($query) > 0) {
$user_id = user_id_from_username($username); // To here. So now this is only called when the credentials are correct
return true;
} else {
return false;
}
}
}
但您应该真正开始使用mysqli_*
或PDO
,从PHP7开始不推荐使用mysql_*
。也不要信任md5()
,因为它很容易被破解。使用hash('sha512', md5($password));
尝试以下方法:
$result = mysql_query("SELECT `active` FROM `users` WHERE `username` = '$username'");
$return = mysql_result($result, 0); // Should be 0 or 1, I don't know this for sure. You need to try it out
// If query is a success
if($result) {
if ($return > 0 && $return < 3) {
return true
} else {
return false;
}
}