Possible Duplicate:
How to prevent SQL injection in PHP?
我在免费的 php 服务器上,我无权访问 php.ini 文件并且 magic_quotes 已打开。所以当我通过我的表单页面将记录添加到 mysql 时,我的 php 代码是
$_POST["text"]=trim(stripslashes(mysql_real_escape_string($_POST["text"])));
我的问题:
- 我想消除 magic_quote 效应,因为它会贬值并移除和潜在的恶意用户
以最佳方式输入mysql。那么我上面的代码是正确的还是需要更改,
改进?
谢谢,
只需 stripslashes() 就足以去除魔术引号。
$text = stripslashes($_POST["text"]);
查看在运行时删除魔术引号的更完整示例:http://php.net/manual/en/security.magicquotes.disabling.php
您真的应该换一个 PHP 服务器。自 PHP 5.3.0(2009 年 6 月)起,魔术引号已被弃用。您的 PHP 托管站点已经将近四年没有更新 PHP,并且您面临许多其他错误甚至安全漏洞的风险。是时候转移到另一个主机了。
回复你的评论:
是的,stripslashes只是将请求参数转换为纯文本。
关于是否应该使用mysql_real_escape_string()的问题...
首先,只有在将值插入 SQL 查询时才应该这样做。您不一定要对每个 POST 值都这样做,因此将转义应用于所有内容是愚蠢的。
打个比方,这就像将晚餐放入冰箱储存容器之前您知道您将吃多少以及剩下多少。 :-)
其次,您根本不应该再使用 mysql_* 函数。他们是deprecated从 PHP 5.5.0 开始,它们将在未来的 PHP 版本中删除。您现在应该开始使用 mysqli_* 或 PDO 函数。
第三,您根本不应该对 SQL 查询中的动态值使用转义。相反,使用带参数的准备好的查询。与使用 mysql_real_escape_string() 相比,参数化查询更安全、更易于编码且运行速度更快。
关于你的下一条评论:
不,我不认为你已经明白了。
如果你想插入 $_POST["text"] 到一个 SQL 查询中,并且魔术引号是打开的,你可以这样做:
// remove the magic quotes simply with stripslashes():
$text = stripslashes($_POST["text"]);
// prepare an SQL statement, using a ? placeholder instead of interpolated value
$stmt = $mysqli->prepare("INSERT INTO mytable (mytext) VALUES (?)");
// always check for an error on prepare, you might have made a syntax error,
// or the table might not exist, etc.
if ($stmt === false) {
die($mysqli->error);
}
// bind one PHP variables for each parameter placeholder in the query
$stmt->bind_param("s", $text);
// then execute! MySQL will use the values of the PHP variables you bound
// in place of the placeholders
$status = $stmt->execute();
// always check for an error on execute too, because the value of the parameter
// might cause the query to fail, e.g. conflicting with another value in a
// unique column, etc.
if ($status === false) {
die($stmt->error);
}
如果使用查询参数,则不会出现需要使用mysqli_real_escape_string()的情况。
如果您需要更多帮助,这里有一个关于 mysqli 的教程,其中包含显示绑定(bind)参数的示例: