不太了解SQL注入

时间:2012-09-02 05:41:42

标签: php sql sql-injection

我已经阅读了很多关于sql注入的知识,我理解它是如何导致问题的(即:DROP TABLE _ _等)。但我不确定我所遵循的教程实际上是如何防止这种情况发生的。我只是在学习PDO,我想我理解它。

这段代码是否可以安全地从SQL注入?,为什么会这样? (使用这些准备好的语句需要花费更多的工作,所以我想确保我不仅浪费时间 - 如果代码可以改进,请告诉我!

$conn = new PDO("mysql:host=$DB_HOST;dbname=$DB_DATABASE",$DB_USER,$DB_PASSWORD);

// Get the data
$firstname = $_POST["v_firstname"];
$lastname =  $_POST["v_lastname"];
$origincountry =  $_POST["v_origincountry"];
$citizenship = $_POST["v_citizenship"];
$gender = $_POST["v_gender"];
$dob = $_POST["v_dob"];
$language = $_POST["v_language"];
$landing = $_POST["v_landing"];
$email = $_POST["v_email"];
$phone = $_POST["v_phone"];
$cellphone = $_POST["v_cellphone"];
$caddress = $_POST["v_caddress"];
$paddress = $_POST["v_paddress"];
$school = $_POST["v_school"];
$grade = $_POST["v_grade"];
$smoker = $_POST["v_smoker"];
$referred = $_POST["v_referred"];
$notes = $_POST["v_notes"];


//Insert Data
$sql = "INSERT INTO clients (firstname, lastname, origincountry, citizenship, gender, dob, language, landing, email, phone, cellphone, caddress, paddress, school, grade, smoker, referred, notes) 
        VALUES (:firstname, :lastname, :origincountry, :citizenship, :gender, :dob, :language, :landing, :email, :phone, :cellphone, :caddress, :paddress, :school, :grade, :smoker, :referred, :notes)";
$q = $conn->prepare($sql);
$q->execute(array(':firstname'=>$firstname,
                  ':lastname'=>$lastname,
                  ':origincountry'=>$origincountry,
                  ':citizenship'=>$citizenship,
                  ':gender'=>$gender,
                  ':dob'=>$dob,
                  ':language'=>$language,
                  ':landing'=>$landing,
                  ':email'=>$email,
                  ':phone'=>$phone,
                  ':cellphone'=>$cellphone,
                  ':caddress'=>$caddress,
                  ':paddress'=>$paddress,
                  ':school'=>$school,
                  ':grade'=>$grade,
                  ':smoker'=>$smoker,
                  ':referred'=>$referred,
                  ':notes'=>$notes));

3 个答案:

答案 0 :(得分:4)

是的,代码是安全的,因为PDO将正确转义并为您引用参数数组。

答案 1 :(得分:1)

您的代码是安全的SQL注入,因为您使用的是paramaterized查询,这基本上意味着一旦构建了查询并将其发送到sql server,它就会被转义,同样可以通过使用php的内置函数来实现{ {1}}。

以下视频是关于来自OWASP的sql注入的精彩信息视频: SQL Injection

答案 2 :(得分:0)

规则是:不要手工构造sql,你可以在其中执行以下操作:

sqlStatement = 'select field1, field2, field3 from mytable where index = '' + myVariable + ''

以上情况很危险,因为如果您的应用允许用户将数据传递到myVariable,他们可能会将完整的SQL命令发送到您的数据库服务器。

如上所述,使用参数化查询是解决方案。