Securing dynamic MySQL statement using whitelist + pdo?
-
18-10-2022 - |
Pregunta
I have been reading this:
How can I prevent SQL injection in PHP?
and I'm thinking of using this whitelist strategy to create very dynamic mysql statement for CRUD.
so my idea is to build 4 functions, buildSelectStatement, buildInsertStatement, buildDeleteStatement, buildUpdateStatement and each function will help me to build the sql statement. For example, the "buildSelectStatement" will take the following arguments:
$selects, $whitelist_selects, $where, $whitelist_where, $orders, $whitelist_orders, $order_syntax, $whitelist_order_syntax, e.g:
$whitelist_select = array("id", "username", "hashed_password", "creation_date", "any other columns in my table"); //all columns in table
$selects = array("id", "username"); //contains fields I want to select
$whitelist_orders = array("creation_date");
$orders = array("creation_date");
$whitelist_order = array("id", "username", "creation_date"); //fields that can be sorted
$order_syntax = "DESC";
$whitelist_order_syntax = array("ASC", "DESC");
$where = ...
... ...
then inside the function I'll use array_search to compare $whitelist_select against $selects, $whitelist_orders against $orders etc. to help me to build a dynamic statement like:
SELECT `id`, `some_field` FROM user_table WHERE `username` = :username
SELECT `hashed_password` FROM user_table ORDER BY creation_date DESC
then I'll create a generic function to take the statement and execute it. ie.
//I used buildSelectStatement() to get $query as well as $bind_array
protected function getSelectResult($query, $bind_array) {
$this->stmt = $this->dbh->prepare($query);
foreach ($bind_array as $param=>$value) {
$this->stmt->bindValue($param, $value, findBindType($value));
}
...
//execute
//then return result
}
is this safe? is there any thing I should worry about?
No hay solución correcta