如何处理包含引号(等)的用户输入?
我有一个标准的文本输入字段。它从 $_POST
获取它的值,我用它来构建 SQL 查询(ODBC,不仅仅是 MySQL,如果这有影响的话(或者实例,我不能使用 mysql_escape_string() ))。
我正在构建的查询在 PHP 上有单引号,在 SQL 上有双引号。例如:
$sql = 'SELECT * FROM ' . $table . ' WHERE field="' . $_POST['some_field'] . '"";
如果用户在输入中包含双引号,例如 6" 扳手
,则我会在不平衡字符串上收到 SQL 错误(单引号,如 O'reilly
中所示)没有问题)。
再次,我使用的是 ODBC 接口,而不是 MySQL,
这只是 addslashes()
的问题吗?魔术报价?
更新: PHP 手册提到了魔术引号......
自 PHP 5.3.0 起,此功能已弃用。强烈建议不要依赖此功能。
(并不是说他们提出了替代方案;事实上,它还说 PHP 6 中将删除魔术引号)
答案应该是使用准备好的语句吗?
I have a standard text input field. It get it's value from $_POST
and I use it to build an SQL query (ODBC, not just MySQL, if that makes a difference (or instance, I can't use mysql_escape_string() ) ) .
The query which I am building has single quotes on the PHP and double quotes on the SQL. E.g.:
$sql = 'SELECT * FROM ' . $table . ' WHERE field="' . $_POST['some_field'] . '"";
If the user includes a double quote in his input e.g 6" wrench
the I get an SQL error on the unbalanced string (a single quote, as in O'reilly
gives no problem).
What's the correct way to handle this? Again, I am using the ODBC interface, not MySQL.
Is it just a matter of addslashes()
? Or magic quotes?
Update: the PHP manual says of magic quotes ...
This feature has been DEPRECIATED as of PHP 5.3.0. Relying on this feature is highly discouraged.
(not that they suggests an alternative; in fact, it also says that magic quotes will be dropped in PHP 6)
Should the answer be to use prepared statements?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 PDO 准备好的语句。它支持 ODBC
Use PDO prepared statements. It supports ODBC
使用
odbc_prepare
和odbc_execute
就像 PDOUse
odbc_prepare
andodbc_execute
like PDO甚至更简单...为什么不直接使用 htmlspecialchars 呢?
https://www.php.net/manual/en/function.htmlspecialchars。 我的意思是,它更快,而且
我假设您为用户提供一个允许他们使用引号的数据字段的原因是因为您将在某个时刻打印该数据。这仍然是可行的,并且您不必更改存储数据的位置。
Even easier... why not just use htmlspecialchars?
https://www.php.net/manual/en/function.htmlspecialchars.php
I mean, it's faster, and I'm assuming that the reason why your giving users a data field that allows them to use quotes is because your going to print that data back out at some point. Which is still doable, and you don't have to change around where you store your data.