How to use whitelists and prepared-statements with Postgresql in php?

社会主义新天地 提交于 2019-12-24 00:34:22

问题


I understand that I need to implement whitelists and prepared-statements into my php code. But I'm not sure how to do this with Postgresql and is it really necessary for my code? I'm using select lists to pass the users selected values to the query.

<?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);

?>

回答1:


White Listing

Your code in it's current form is very dangerous, not only do you allow the user to decide what fields should be selected but you also allow him to decide what tables to query on. You should definitely carry out white list checking on these. eg:

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

Similarly you should validate the field lists. But field list validation is going to be rather complicated because your fields are going to be dependent on the table. I suggest creating arrays and checking that the selection is in it.

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

Prepared Statements

As you know prepared statements can only be used to bind parameters. They cannot be used to fill in table names and column names. That's why you need both prepared statements and white listing. I recommend using PDO. It might look something like

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


来源:https://stackoverflow.com/questions/37920413/how-to-use-whitelists-and-prepared-statements-with-postgresql-in-php

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