如何修复此登录功能

时间:2019-04-26 11:13:35

标签: php session cookies login passwords

我的PHP代码中具有以下两个功能:

function admin_checker($username,$password)
{
    $username=remove_extra_in_string($username);
    $password=remove_extra_in_string($password);
    $q='select * from `admin` where `username`="'.$username.'" and `password`="'.$password.'"';
    $result=@mysqli_query($conn, $q);
    $_COOKIE['username'] = $result["username"];
    $_COOKIE['password'] = $result["password"];
    if(@mysqli_num_rows($result)==1)
        return 1;
    else
        return 0;
}

function remove_extra_in_string($string)
{
    $extra=array('\'','"','`','/','*',';',' ','--');
    $string=str_replace($extra,'',$string);
    return $string;
}

然后按此检查:

if(admin_checker($_COOKIE['username'],$_COOKIE['password'])==1)
{ echo "ok"; } else { echo "not ok"; }

但是不知何故,我不知道我在做什么错了?

1 个答案:

答案 0 :(得分:0)

首要也是最重要的一点:永远不要将密码存储为纯文本,永远不要将用户数据保存在COOKIE中。 接下来-不要使用您自己的函数remove_extra_in_string(),不要使用内置的mysqli_real_escape_string甚至更好的方法-使用准备好的语句:https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

这种情况是,如果您以纯文本形式存储密码,则可能会有更多具有相同密码和用户名的记录,并且它将返回值!= 1,所以它将为FALSE。

它也可能会失败,因为在调用admin_checker()时没有设置COOKIES,因此$ username和$ password等于null。