dongzg2006 2012-09-22 07:13
浏览 12
已采纳

将数组中的$ _POST数据直接插入MySQL语句有多安全?

I have created a simple function to post data into a mysql table using a function and an array. The array is built from $_POST items on a form. What I would like to know is: Are there potential security holes that I am not seeing?

Here is the function:

            public function add_sql_data($table,$array){
            $tot = count($array);
            $c=0;
            foreach($array as $k => $v){
                $fields = $fields.$k;
                $values = $values."'".$v."'";
                $c++;
                if($c < $tot){
                    $fields = $fields.","; 
                    $values = $values.","; 
                }
            }
            $sql = "INSERT INTO ".$table."(".$fields.") values(".$values.")";
            if (mysql_query($sql)){
                return "succesfull";
            }else{
                return "error";
            }
        }

I have tried to use the small amount of PHP I know to create a SQL injection, but it seams to me that the array is actually stopping any harmful syntax to run. Thanks!!

  • 写回答

4条回答 默认 最新

  • dongxiaoshe0737 2012-09-22 08:41
    关注

    Not safe at all

    In the sql in the question - there is no sanitization or escaping. Consider what will happen with individual form inputs like this:

    • 'and he said "no way jose"'
    • 'blah ")'
    • '"), (select field from table limit 1))--'

    In the first, there's going to a syntax error of some sort, and also in the second.

    The 3rd is just a hint at the tip of an iceberg of the sort of injection you are making possible. Here, we're injecting the value of another table into this insert statement, if that field is visible to the end user they can do things like this to explore your database and gain access to information they shouldn't be able to see. Just google sql injection and you'll find an endless list of examples.

    The right way

    You really, really should be using PDO and preferably prepared statements instead of the older mysql_* functions.

    An example of something similar to what you're doing that is safe from injection is:

    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    $stmt = $dbh->prepare("INSERT INTO table (name, value) VALUES (?, ?)");
    $stmt->bindParam(1, $name);
    $stmt->bindParam(2, $value);
    
    // insert one row
    $name = 'one';
    $value = 1;
    $stmt->execute();
    

    In this way, it doesn't matter what $name or $value are - they will be escaped appropriately.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗