Whitelisting helper function

  1. Comments

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$allowedtrue);
    if (
$key === false) { 
        throw new 
InvalidArgumentException($message); 
    } else {
        return 
$value;
    }
}

The function accepts three parameters:

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: