我担心SQL注入.这安全吗


I am worried about SQL Injections. Is this safe?

我正在启动一个非常基本的站点,它使用单行表单发布到数据库中,然后在页面上回显该$comment变量。我不了解PDO,但如果我真的需要它来做这么简单的事情,我愿意学习。

else
mysql_query("INSERT INTO posts (postid, post_content)
VALUES ('', '$comment <br />')");
}
mysql_close($con);

在此代码上方,我有基本的strpos命令来阻止一些我不想发布的内容。

从我

这样做的方式来看,我会遇到注射的任何问题吗?

不,不安全,你需要使用mysql_real_escape_string来逃避$comment

但是,PDO并不难,可以使您的代码更强大。

// create the connection. something like mysql_connect/mysql_error
try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
// create the prepared statement.
$stmt = $dbh->prepare("INSERT INTO posts (postid, post_content) VALUES (?, ?)");
// execute it with parameters.
$stmt->execute(array('', $comment.'<br>'));

是的,这很危险。 人们所要做的就是先加上一个引号,然后加上他们想要的SQL代码。 如果要以旧方式修复它或使用 PDO 准备语句作为较新的方法,请在此语句之前使用 $comment = mysql_real_escape_string($comment)。以下是文档中的基本示例:

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

这容易受到sql注入的影响,因为您的$comment是从用户输入的,他们也可以输入一些SQL命令,而您的PHP代码最终将执行相同的命令。

请考虑将$comment值设置为'TRUNCATE TABLE USERS;' USERS 表可以是可能对应用至关重要的任何内容。

在PHP中,我相信您可以通过使用mysql_real_escape_string()来防止SQL注入。请继续阅读。

有关 abt SQL 输入的详细信息,请参阅此文档:https://docs.google.com/document/d/1rO_LCBKJY0puvRhPhAfTD2iNVPfR4e9KiKDpDE2enMI/edit?pli=1

将表单输入数据绑定到 mysql 查询是 sql 注入的完美解决方案。为此,请使用 binaParam 方法。

不,仅从您在此处发布的代码来看,您不会受到SQL注入的保护。下面是一个简单的$comment示例:

'), (null, (select concat(user(),':',password) s from mysql.user where concat(user,'@',host)=user() LIMIT 1) --

这将添加另一行,其中包含当前用户的登录凭据。有了LOAD_FILE他还可以从您的文件系统中读取文件。他还可以在文件系统上写入任意文件:

' + (select '<?php echo "Hello, World!";' into dumpfile '/path/to/your/document_root/foobar.php')) --

使用这种技术,攻击者可以将任意文件上传到您的服务器,例如 Web shell 以在您的系统上运行任意命令。

因此,

您绝对必须保护自己免受SQL注入的影响,因此使用预准备语句或参数化语句的自动转义比使用mysql_real_escape_string等函数的手动转义更受欢迎。