防止PHP中的SQL注入攻击

问题描述 投票:0回答:1

我想防止对这段PHP代码的SQL攻击(这只是课堂上的练习)。可以通过将@mail设置为等于'); DROP TABLE PURCHASE; --

来轻松利用
$db = new SQLite3 ($db_name);

$sql = sprintf ("INSERT INTO PURCHASE (quantity, name, password, mail) 
                 VALUES ('%s', '%s', '%s', '%s')\n",
                 $Quantity, $Name, $Password, $Mail );

echo $sql;
if (!$db->exec ($sql)) {
    throw new Exception($db->lastErrorMsg());
}

我试图通过传递这样的参数来防止这种情况,但是我得到了500 Internal Server Error

$db = new SQLite3 ($db_name);

$sql = $db->prepare("INSERT INTO PURCHASE(quantity, name, password, mail)
            VALUES (:Quantity, :Name, :Password, :Mail)");

$sql->bindValue(':Quantity', $Quantity, SQLITE3_TEXT);
$sql->bindValue(':Name', $Name, SQLITE3_TEXT);
$sql->bindValue(':Password', $Password, SQLITE3_TEXT);
$sql->bindValue(':Mail', $Mail, SQLITE3_TEXT);

echo $sql;
if (!$db->exec ($sql)) {
    throw new Exception($db->lastErrorMsg());
}

我该如何解决?

php sql sqlite security sql-injection
1个回答
2
投票

SQLite3::exec用于执行查询字符串,而不是准备的语句。您需要改用SQLite3::exec。更改:

SQLite3Stmt::execute

SQLite3Stmt::execute

注意,您不能if (!$db->exec ($sql)) { throw new Exception($db->lastErrorMsg()); } ,因为它是一个对象,而不是简单的类型。如果要查看if (!$sql->execute()) { throw new Exception($db->lastErrorMsg()); } 对象的外观,则需要echo $sqlSQLite3Stmt

© www.soinside.com 2019 - 2024. All rights reserved.