首页 > 解决方案 > 如何修复此登录功能

问题描述

我的 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"; }

但不知何故它没有通过,我不知道我在这里做错了什么?

标签: phpsessioncookiesloginpasswords

解决方案


首先也是最重要的一点:永远不要将密码存储为纯文本,也永远不要将用户数据保存在 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。


推荐阅读