在PHP的登录页面中防止SQL注入 [英] Preventing SQL Injection in Login Page in PHP

查看:305
本文介绍了在PHP的登录页面中防止SQL注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个登录页面(login.php),下面是我尝试使用mysqli_prepare来验证用户身份的代码:

I have a login page (login.php) and below is the code I am trying to use to authenticate the user by using mysqli_prepare:

if(!$_POST["username"] || !$_POST["password"])
{
    echo "Username and Password fields are mandatory.";
}
else
{
    $unsafe_username = $_POST["username"];
    $unsafe_password = md5($_POST["password"]);
    $query=mysqli_prepare($con, "select user_id from users where user_name= ? and password= ? ");
    $query->bind_param("ss", $unsafe_username, $unsafe_password);
    $query->execute();
    $data = $query->get_result();

    if(is_array($data))
    {
       echo "Login successful";
    }
    else
    {
       echo "Login failed";
    }
}

以下是用于建立MYSQL连接的代码:

Below is the code used for making MYSQL connection:

function connect_database()
{
    $con = mysqli_connect("servername", "username", "", "dbname");
    if (!$con) 
    {
        $con = "";
        echo("Database connection failed: " . mysqli_connect_error());
    }
    return $con;
}

通过使用mysqli_prepare,我收到以下警告和错误消息:

By using mysqli_prepare, I am getting following warning and error messages:

Warning: mysqli_prepare() expects exactly 2 parameters, 1 given

Fatal error: Call to a member function bindParam() on null

两天前,我问了类似的问题,但没有得到完整的解决方案. (防止SQL注入PHP和MySQL中的登录页面).

I asked the similar question two days ago, but did not get any complete solution. (Prevent SQL Injection to Login Page in PHP and MySQL).

请帮助我解决问题.这是阻止我的数据库进行SQL注入的最佳方法吗?

Please help me in resolving the problem. Is it the best approach to prevent my DB from SQL Injection?

推荐答案

缺少连接变量$con

$query=mysqli_prepare($con,"select user_id from users where user_name= ? and 
password= ? ");      

并对此进行更改

$query->bind_Param("ss", $unsafe_username, $unsafe_password);
           ^^^ 

这篇关于在PHP的登录页面中防止SQL注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆