Whitelisting helper function
There are edge cases when we cannot use a prepared statement for a variable to be used in the query. Given placeholders can substitute only data literals (i.e. strings and numbers), we need something to protect other query pars, such as keywords or identifiers that may happen to be added to the query dynamically.
In this case we have to use the white list approach, filtering our data against a predefined list of allowed values. To ease the routine, I wrote a handy function that will let us to get the safe value in one line! Here it is:
function white_list(&$value, $allowed, $message) {
if ($value === null) {
return $allowed[0];
}
$key = array_search($value, $allowed, true);
if ($key === false) {
throw new InvalidArgumentException($message);
} else {
return $value;
}
}
The function accepts three parameters:
- the value to be checked. It is passed by reference so it won't raise an error in case a variable is not set. It would allow us to assign a default value if no value is provided
- the list of allowed values. The first one would serve as a default value
- the error message to throw so a programmer would know what caused the error
Having such a function at hand we can have our code much more tidy and concise:
$orderby = white_list($_GET['orderby'], ["name","price","qty"], "Invalid field name");
$direction = white_list($_GET['direction'], ["ASC","DESC"], "Invalid ORDER BY direction");
$query = "SELECT * FROM `table` ORDER BY `$orderby` $direction"; // sound and safe!
Related articles:
- (The only proper) PDO tutorial
- PDO Fetch Modes
- Fetching objects with PDO
- Simple yet efficient PDO wrapper
- An SQL injection against which prepared statements won't help
- A fair comparison of mysqli vs. PDO
- Your first database wrapper's childhood diseases
- Authenticating a user using PDO and password_verify()
- MCVE or How to debug database interactions with PDO
- A cargo cult prepared statement
Add a comment
Please refrain from sending spam or advertising of any sort.
Messages with hyperlinks will be pending for moderator's review.
Markdown is now supported:
>
before and an empty line after for a quote