在 PHP 和 MySQL 中防止 SQL 注入登录页面 [英] Prevent SQL Injection to Login Page in PHP and MySQL

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

问题描述

下面是我的登录页面的 PHP 代码.

Below is my PHP code for login page.

if(!$_POST["username"] || !$_POST["password"])
{
    echo "Username and Password fields are mandatory.";
}
else
{
    $query="select user_id from users where user_name='".$_POST["username"]."' and password='".md5($_POST["password"])."' ";
    .....
    .....
}

我认为,这是 SQL 注入的易受攻击代码.我应该在此代码中修改什么以防止 SQL 注入我的 MYSQL 数据库?

I think, this is vulnerable code for SQL Injection. What should I modify in this code to prevent SQL Injection to my MYSQL database?

我使用以下代码连接到我的 MySQL 数据库:

I am using following code to connect to my MySQL database:

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

我正在尝试使用 mysqli_prepare,但出现错误:

I am trying to use mysqli_prepare, but getting errors:

$unsafe_username = $_POST["username"];
$unsafe_password = md5($_POST["password"]);
$query=mysqli_prepare("select user_id from users where user_name= ? and password= ? ");
$query->bindParam("ss", $unsafe_username, $unsafe_password);
$query->execute();

我收到以下错误:

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

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

推荐答案

使用准备好的语句,

http://php.net/manual/en/pdo.prepared-声明.php

$stmt = mysqli->prepare("select user_id from users where user_name= ? and password= ?");
$stmt->bindParam("ss",$username,$pass);
$stmt->execute();

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

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