pdo 防止 sql 注入 [英] pdo to prevent sql injection

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

问题描述

我正在尝试将访问者的输入插入数据库.
这有效,但是 - 这足以防止 sql 注入吗?

I'm trying to insert the visitor's inputs into a database.
This works, but - is this good enough to prevent sql injection ?

<?php
$db_host = "localhost";
$db_name = "db_qadenza";
$db_user = "root";

$odb = new PDO ("mysql:host=" . $db_host . ";dbname=" . $db_name, $db_user);

if(isset($_POST['Submit']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$mail = $_POST['mail'];
$confirm_key=md5(uniqid(rand()));

$q = "INSERT INTO members (user, pass, mail, confirm_key)
VALUES(:user, :pass, :mail, :confirm_key);";

$query = $odb->prepare($q);
$results = $query->execute(array(
":user"=>$user,
":pass"=>$pass,
":mail"=>$mail,
":confirm_key"=>$confirm_key,
));

exit();
}
?>

推荐答案

您的代码有两个问题.

  1. 您正在使用模拟准备好的语句.这是 PDO_MYSQL 驱动程序的默认行为.要规避它,您应该添加:

  1. You are using emulated prepared statements. This is the default behavior for PDO_MYSQL driver. To circumvent it, you should add:

$odb->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

结合与数据库通信的缺失字符集,可以使您的代码对注入开放.要建立连接,您应该使用:

In combination with missing charset for the communication with DB, which can make your code open to injections. For establishing the connection you should use:

$odb = new \PDO('mysql:host=localhost;dbname=******;charset=UTF-8', 
                'user', 'pass');

  • 您的密码散列方法不安全(或者实际上不存在).相反,您应该使用 crypt() 函数使用 CRYPT_BLOWFISHPBKDF2 和每个密码的不同盐.

  • Your method of hashing password is insecure (or, actually, does not exist). Instead you should use crypt() function with CRYPT_BLOWFISH or PBKDF2 and different salt for each password.

    另外,你可以考虑使用 bindParam() 设置命名参数的方法,因为通过 execute() 设置它们会将值绑定为 PDO::PARAM_STR,但是有 其他选项,您可能会觉得有用.

    Also , you might consider using bindParam() method for seting the aluse of named parameters, since setting them through execute() would bind the values as PDO::PARAM_STR, but there are other options, that you might find useful.

    这篇关于pdo 防止 sql 注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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