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条)

报告相同问题?

悬赏问题

  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”