PHP无参数绑定预防SQL注入
可能的重复:
如何防止 PHP 中的 SQL 注入?
我正在制作一个视频我的大学图书馆的流媒体网站。我正在使用 PHP 和 MySql。我在这个项目中没有使用任何参数化查询。
最近我开始了解SQL注入。现在我的代码已经快完成了,过两天就要提交项目了,那么我现在如何确保我的代码不会出现SQL注入呢?
我现在无法将整个事情转换为参数化接口。我现在应该怎么做才能避免我的网站上出现 SQL 注入?
Possible Duplicate:
How to prevent SQL injection in PHP?
I am working for a video streaming website for my college library. I am using PHP and MySql. I have not used any parameterized queries in this project.
Recently I came to know about SQL injections. Now that my code is almost done and I have to submit the project in the next two days, how can I now ensure that my code is not SQL injection prone?
Converting the whole thing in to a parameterized interface is what I can't do now. What should I do now to avoid SQL Injections on my website?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
防止 SQL 注入(如果不使用准备语句)的基本思想是转义数据。
当您将一些预期的整数值注入 SQL 查询时,请使用
intval 确保它是一个整数()
。当表中有小数/数字字段时,请使用
floatval()
。当表中有字符串 (char, varchar, text) 字段时,请使用 API 提供的函数来转义字符串:
mysql_real_escape_string()
mysqli_real_escape_string()
PDO::quote()
The basic idea to prevent SQL injections (if not using Prepared Statements) is to escape your data.
When you inject some expected integer value into an SQL query, make sure it's an integer, using
intval()
.When you have a decimal/numeric field in your table, use
floatval()
.And when you have a string (char, varchar, text) field in your table, use the function provided by your API to escape strings :
mysql_real_escape_string()
mysqli_real_escape_string()
PDO::quote()
我真的建议您返回并使用参数化查询正确执行此操作。这是实现安全的唯一坚实道路。一旦开始,完成此操作可能不会花费太长时间。
您还应该知道网站永远不会“完成”。当您启动网站时,您的工作才刚刚开始。当您了解安全问题时解决它们是其中的一部分,这也不例外。
I really recommend that you go back and do it right with parameterized queries. It is the only solid path towards security. It likely won't take too long to do this once you get started.
You should also know that websites are never "finished". When you launch a site, your work has just begun. Fixing security troubles as you learn about them is part of it, and this is no different.
您需要确保使用 PHP 函数
mysql_real_escape_string
对 SQL 查询中使用的任何用户提供的输入进行转义,并且如果您允许人们提交文本来运行htmlentities
提供的文本,因此 XXS 是不可能的。如果可能,白名单用户提供输入并丢弃其他任何内容这只是触及您可以做的事情的表面,但要研究查询转义和防止跨站点脚本编写。
You'll want to make sure any user provided inputs that get used in SQL queries are escaped using the PHP function
mysql_real_escape_string
and if you are letting people submit text to runhtmlentities
on the provided text so XXS isn't possible. If possible, white-list user provided input and discard anything elseThis is just touching the surface of what you can do but look into query escaping and preventing cross site scripting.
使用 PDO(或者 mysqli 或一些抽象层)和准备好的语句。
简单示例:
在此示例中,
$unsafe_id
可以安全使用。引用手册页:Use PDO (or alternatively mysqli or some abstraction layer) and prepared statements.
Quick example:
In this example,
$unsafe_id
will be safe to use. To quote the manual page: