Am I safe from SQL-injections?

。_饼干妹妹 提交于 2019-12-12 14:19:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!