这可以 SQL 注入吗?
Can this be SQL injected?
我想知道我的代码是否真的受到了 SQL 注入的保护。我的网站以前被注入过,但我从来没有真正理解如何防止它。这是我插入评论的代码:
if ($_POST['comment']) {
$comment = strip_tags(nl2br(mysql_real_escape_string($_POST['comment'])));
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO posts (comment, authorid)
VALUES ('$comment', '$uid')";
// use exec() because no results are returned
$conn->exec($sql);
echo '<div style="width: 98%; max-width: 98%; border: 1px solid white; background-color: green; color: white; vertical-align: text-top; text-align: center;">Your comment was added to the wall!</div><br>';
}
是的,它可能会被注入:您似乎没有保护您的 $uid
变量。此外,在 转义之后堆叠 nl2br
和 strip_tags
是一个坏主意 - 你想离开 mysql_real_escape_string
作为 last 操作以避免任何过滤器交互影响。
更一般地说,您应该使用准备好的语句,而不是字符串插值来构建SQL 查询。它更简单、更高效、更安全并且需要更少的代码。您可以使用 $conn->prepare
创建准备好的语句并使用任意参数执行它:
$stmt = $conn->prepare("INSERT INTO posts (comment, authorid) VALUES (?, ?)");
$stmt->execute(array($comment, $uid));
无需转义。
我想知道我的代码是否真的受到了 SQL 注入的保护。我的网站以前被注入过,但我从来没有真正理解如何防止它。这是我插入评论的代码:
if ($_POST['comment']) {
$comment = strip_tags(nl2br(mysql_real_escape_string($_POST['comment'])));
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO posts (comment, authorid)
VALUES ('$comment', '$uid')";
// use exec() because no results are returned
$conn->exec($sql);
echo '<div style="width: 98%; max-width: 98%; border: 1px solid white; background-color: green; color: white; vertical-align: text-top; text-align: center;">Your comment was added to the wall!</div><br>';
}
是的,它可能会被注入:您似乎没有保护您的 $uid
变量。此外,在 转义之后堆叠 nl2br
和 strip_tags
是一个坏主意 - 你想离开 mysql_real_escape_string
作为 last 操作以避免任何过滤器交互影响。
更一般地说,您应该使用准备好的语句,而不是字符串插值来构建SQL 查询。它更简单、更高效、更安全并且需要更少的代码。您可以使用 $conn->prepare
创建准备好的语句并使用任意参数执行它:
$stmt = $conn->prepare("INSERT INTO posts (comment, authorid) VALUES (?, ?)");
$stmt->execute(array($comment, $uid));
无需转义。