doucuo9126 2013-06-09 13:12
浏览 34
已采纳

PHP通过循环遍历$ _POST全局[关闭]自动为PDO语句生成参数

I have written this function below to return the values from the $_POST global that can be used in the PDO statement. I just want suggestions if this is a good way to do it. I know that the "implode" part might not be very flexible but i would like to know how this can be improved. Any help with the logic and improving the function is deeply appreciated. Thanks.

/**
 * This function loops through the $_POST global and returns parameters that can be used in
 * a PDO statement directly. Note : For this function to work properly the 
 * PDO::ATTR_EMULATE_PREPARES should be set to "false"
 * like so "$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false)".
 * @param  Array $exclude This is an array of keys in $_POST that you want the function to ignore
 * @return Array The function returns an array that can be used as parameters for the PDO statement
 */
function get_params($exclude = array()) {
    $keys = array();
    $values = array();
    $placeholder_keys = array();
    $params = array();

    foreach ($_POST as $key => $value) {
        if(!in_array($key, $exclude)) {
            $keys[]             = $key;
            $placeholder_keys[] = ":" . $key;
            if(is_array($value)){
                $value = implode(",", $value);
            }
            $values[] = $value;
        }
    }

    $comma_sep_keys = implode(",", $keys);
    $comma_sep_placeholder_keys = implode(",", $placeholder_keys);

    $params['keys'] = $keys;
    $params['values'] = $values;
    $params['placeholder_keys'] = $placeholder_keys;
    $params['comma_sep_keys'] = $comma_sep_keys;
    $params['comma_sep_placeholder_keys'] = $comma_sep_placeholder_keys;

    return $params;
}
  • 写回答

2条回答 默认 最新

  • dtoqemais553654797 2013-06-09 13:15
    关注

    You're not sanitizing the keys at all. What if an array element is:

    array(
        "foo = ''; DROP TABLE users; --" => 'baz'
    )
    

    This leaves you wide open to SQL injection. You're placeholding the values, but in return you're blindly concatenating unsanitized keys into your queries.

    You're also imploding array values into a single string; do you really want to insert them as the single value "foo,bar,baz" when they were an array originally?

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

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失