【问题标题】:Convert into secure PDO statement?转换成安全的 PDO 语句?
【发布时间】:2012-10-16 20:59:09
【问题描述】:

有人可以告诉我如何使用 PDO 将我当前的 UPDATE tablename SET column 转换为安全可靠的语句以防止 SQL 注入吗?我试图更好地理解绑定和 PDO,但在使用 PDO 进行设置时遇到了麻烦。这是我目前拥有的常规 msqli

<?php

session_start();
$db = mysqli_connect("hostname", "username", "password", "dbname"); 
$username = $_SESSION['jigowatt']['username'];
mysqli_query($db, "UPDATE login_users SET Points=Points+15 WHERE username='$username'");


?>

【问题讨论】:

  • 您也可以使用程序方式进行保护..
  • 您可以修改手册页中的第一个示例(或示例 #3):php.net/manual/en/pdo.prepared-statements.php
  • 我会再看一遍,谢谢:)
  • 假设用户名是字母数字,并且您将用户名放入会话中并且它不是某种用户输入,这里没有注入的机会。
  • 看看bobby-tables.com/php.html的例子。

标签: php mysql pdo mysqli sql-injection


【解决方案1】:

MySQL

您不需要 PDO 或 MySQLi。 mysql_real_escape_string保护你免受sql注入:

$name = 'Bob';
$age = 25;
$description = "' OR 1=1"; // a SQL injection string

$query = "
UPDATE people(name, age, description) 
VALUES ('".mysql_real_escape_string($name)."', ".(int) $age.", '".mysql_real_escape_string($description)."');";

// a secure query execution
$result = mysql_query($query);

PDO

PDO::quote()

PDO::quote() 等于mysql_real_escape_string

$pdo = new PDO(...);

$name = 'Bob';
$age = 25;
$description = "' OR 1=1"; // a SQL injection string

$query = "
UPDATE people(name, age, description) 
VALUES (".$pdo->quote($name).", ".(int) $age.", ".$pdo->quote($description).");";

// a secure query execution
$result = $pdo->query($query);

使用准备好的语句

您可以使用准备好的语句。您可以将空洞查询放在准备好的语句中,但最好对变量使用占位符:

$pdo = new PDO(...);

$name = 'Bob';
$age = 25;
$description = "' OR 1=1"; // a SQL injection string

$query = "
UPDATE people(name, age, description) 
VALUES (:name, :age, :description);";

$stmt = $pdo->prepare($query); // prepare the query

// execute the secure query with the parameters
$result = $pdo->execute(array(
    ':name' => $name,
    ':age' => $age,
    ':description' => $description,
));

【讨论】:

  • 我认为应该是 $stmt-&gt;execute 而不是 $pdo-&gt;execute
猜你喜欢
  • 1970-01-01
  • 2010-11-21
  • 2012-08-12
  • 2013-08-11
  • 2014-11-29
  • 2023-04-09
  • 1970-01-01
  • 2015-12-08
相关资源
最近更新 更多