我目前正在关注Youtube上的一个名为Register& amp;来自Phpacademy的Alex的登录/ PHP教程..我在第5部分,这里是login.php
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'You need to enter a username and password ';
} else if (user_exists($username) === false) {
$errors[] = 'We couldn\'t find that username. Have you registered?';
}
else if (user_active($username) === false){
$errors[] = 'You havn\'t activated your account!';
}
else {
$login = login($username, $password);
if ($login === false) {
$error[] = 'That username/password combination is incorrect';
} else {
$_SESSION['user_id'] = $login;
header('Location: index.php');
exit();
}
}
}
print_r($errors);
?>
这是users.php
<?php
function user_exists($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '.$username'"), 0) == 1) ? true : false;
}
function user_active($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '.$username' AND `active` = 1 ") , 0 ) == 1 ) ? true : false;
}
function user_id_from_username($username){
$username = sanitize($username);
return mysql_result (mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username' "), 0, 'user_id');
}
function login($username, $password){
$user_id = user_id_from_username($username);
$username = sanitize($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;
}
?>
这是输出Array ( [0] => We couldn't find that username. Have you registered? )
我是新来的,提前道歉
答案 0 :(得分:0)
WHERE `username` = '.$username' AND `password` = '.$password'"
删除点
答案 1 :(得分:0)
您的SQL查询将返回错误的结果。否则,如果您输入的用户名为.jond
,则会在数据库中搜索jond
。
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '.$username'"), 0) == 1) ? true : false;
删除查询中.
和$username
之前的$password
。
"SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'"
答案 2 :(得分:0)
您的查询需要稍微调整一下。删除用户名前面的句点,因为它在双引号
中return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'"), 0) == 1) ? true : false;
对于该文件中的其他查询,情况也是如此。正如评论中所提到的,你真的应该从弃用的mysql_ *函数切换到PDO / mysqli,这样你的代码仍然可以在PHP的未来版本中使用,并且你不会对注入黑客开放。
答案 3 :(得分:0)
你的代码整体上非常可怕。你应该 NOT 嵌套你的mysql调用。这样嵌套意味着您认为数据库操作将从不失败。这是一个非常糟糕的假设。
话虽如此,这至少是你问题的一个来源:
return (...snip ... WHERE `username` = '.$username'"), 0) == 1) ? true : false;
^--- here
您在该查询中嵌入了.
,使您的所有用户名都显示为.foo
,而不仅仅是foo
。 user_exists()
,user_active()
AND login()
存在问题。