我担心SQL注入。这样安全吗?

时间:2012-06-28 05:33:11

标签: php mysql

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

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

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

我将如何处理因为我这样做而注射的任何问题?

5 个答案:

答案 0 :(得分:3)

是的,这很危险。所有人要做的就是在他们想要的SQL代码之后添加一个引号。如果您想以旧方式修复它或使用PDO预处理语句作为新方法,请在此语句之前使用$ comment = mysql_real_escape_string($ comment)。以下是documentation

的基本示例
<?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();
?>

答案 1 :(得分:3)

不,这不安全,您需要使用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>'));

答案 2 :(得分:0)

这很容易被sql注入,因为你的$ comment是从用户输入的,他们也可以输入一些SQL命令,你的PHP代码最终会执行相同的操作。

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

在PHP中,我相信您可以使用mysql_real_escape_string()来防范SQL注入。阅读它。

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

不,只根据您在此处发布的代码判断,您不会受到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')) --

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

所以你绝对必须protect yourself against SQL injections使用预准备语句或参数化语句的自动转义比使用mysql_real_escape_string等函数的手动转义更受青睐。