问题
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!
回答1:
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 an int field).
if (!is_numeric($_POST['id'])
die ("Invalid ID");
回答2:
One thing you should do is making shure the ID is integer (which is probably needs to be):
$id = (int)$_POST['id'];
回答3:
if there's something I can do to make it safer
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.
来源:https://stackoverflow.com/questions/5990100/am-i-safe-from-sql-injections