php - 如何在 PHP 中使用 Postgresql 白名单和准备语句?

标签 php postgresql prepared-statement whitelist

我知道我需要在我的 php 代码中实现白名单和准备好的语句。但我不确定如何使用 Postgresql 执行此操作,这对我的代码来说真的有必要吗?我使用选择列表将用户选择的值传递给查询。

<?php

include "connect.php";

$table          = $_POST['tableSelected'];
$field          = $_POST['fieldSelected'];
$attribute      = $_POST['attributeSelected'];
$operator       = $_POST['operatorSelected'];
$fieldList      = $_POST['fieldList'];

$fieldstr = $fieldList . ",ST_AsGeoJSON(ST_Transform(l.geom,4326))";


$sql = "SELECT $fieldstr
        FROM $table l";

if (!empty($field) && !empty($operator) && !empty($attribute)) {
    $sql .= " WHERE {$field} {$operator} '{$attribute}'";
}

echo ($sql);

?>

最佳答案

白名单

当前形式的代码非常危险,您不仅允许用户决定应选择哪些字段,还允许他决定查询哪些表。您绝对应该对这些进行白名单检查。例如:

if($_POST['tableSelected'] == 'acceptable_table1' || $_POST['tableSelected'] == 'acceptable_table2) {
    $table = $_POST['tableSelected']
}

同样,您应该验证字段列表。但是字段列表验证将相当复杂,因为您的字段将依赖于表。我建议创建数组并检查选择是否在其中。

$table1_fields = array('col1','col2',...)
$table2_fields = array('col1','col2',...)

准备好的报表

如您所知,准备好的语句只能用于绑定(bind)参数。它们不能用于填写表名和列名。这就是为什么您需要准备好的声明和白名单。我建议使用PDO 。它可能看起来像

$stmt = $dbh->prepare("SELECT {$fieldlist} FROM {$table} where field = ?");
$stmt->execute(array('somevalue'));

关于php - 如何在 PHP 中使用 Postgresql 白名单和准备语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37920413/

相关文章:

PHP & MySQL : Convert rows and columns to json objects

python - 移动并返回 psycopg2

postgresql 在一个结果中显示两个子列表

java - Postgres 查询必须是 boolean 类型

php - PDO 准备语句 : Replacing the value of a column

PHP 准备语句 - 在 while 循环内进行查询时出现错误

java - 使用预处理语句设置表名

php - 在 MySQL 中存储持续时间的最佳方法是什么

php - 使用php将图像添加到mysql

php - Wordpress DB 字符集从 utf8mb4 更改为 utf8 导致错误