我可以免受 SQL 注入攻击吗?
我使用一个简单的 cms 作为我的网站的后端,我可以在其中更新新闻等。我希望避免 SQL 注入,所以我想知道这段代码是否被认为是安全的,或者我是否可以做一些事情来使其更安全:
if($_POST) {
if(isset($_POST['title']) and (isset($_POST['content']) and ($_POST['added']))) {
$title = "'".mysql_real_escape_string($_POST['title'])."'";
$content = "'".mysql_real_escape_string($_POST['content'])."'";
$added = "'".mysql_real_escape_string($_POST['added'])."'";
if(isset($_POST['id']) && $_POST['id']!=''){
$result = mysql_query("UPDATE news SET title = ".$title.", added =".$added.", content = ".$content." WHERE id = ".$_POST['id']);
$msg = "News Updated Successfully";
}else{
$result = mysql_query("INSERT INTO news (title, content, added) values($title, $content, $added)") or die("err0r");
$msg = "News Added Successfully";
}
}
谢谢,祝你有美好的一天!
I'm using a simple cms as backend to my website where I'm able to update news and such. I want to be safe from SQL-injections, so I'm wondering if this code is considered to be safe or if there's something I can do to make it safer:
if($_POST) {
if(isset($_POST['title']) and (isset($_POST['content']) and ($_POST['added']))) {
$title = "'".mysql_real_escape_string($_POST['title'])."'";
$content = "'".mysql_real_escape_string($_POST['content'])."'";
$added = "'".mysql_real_escape_string($_POST['added'])."'";
if(isset($_POST['id']) && $_POST['id']!=''){
$result = mysql_query("UPDATE news SET title = ".$title.", added =".$added.", content = ".$content." WHERE id = ".$_POST['id']);
$msg = "News Updated Successfully";
}else{
$result = mysql_query("INSERT INTO news (title, content, added) values($title, $content, $added)") or die("err0r");
$msg = "News Added Successfully";
}
}
Thanks and have a great day!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您没有清理
$_POST['id']
。对其执行
intval()
操作,或者(更好)如果 ID 不是整数(假设 ID 是int
字段),则完全拒绝处理。You are not sanitizing
$_POST['id']
.Do an
intval()
on it, or (better) refuse processing altogether if the ID is not an integer (assuming ID is anint
field).你应该做的一件事是确保 ID 是整数(这可能是需要的):
One thing you should do is making shure the ID is integer (which is probably needs to be):
是的,您可以使用 PDO与预准备语句的接口,以便查询与数据(稍后绑定)分开构建,并且不可能进行任何类型的注入。
Yes, you can use the PDO interface with prepared statements, so that the query is built separately from the data (which is bound later) and no kind of injection is ever possible.