Safely inject the values into SQL

Other than using bind in SQL, this is the old school way to solve the SQL query to prevent injection attack

Sample Code

// a sample list of values to use in IN():
$values = [1,4,10,'12a','xy\'z'];

// VERSION 1. For integers: make sure all array elements are integers
$in = implode(',', array_map('intval', $values));

// VERSION 2. For strings: apply PDO::quote() function to all elements
$in = implode(',', array_map([$pdo, 'quote'], $values));

// VERSION 3. Custom sanitization: allow only letters and numbers in strings
$in = implode(',', array_map(function($v) {
    return "'" . preg_replace('/[^a-zA-Z0-9]/', '', $v) . "'";
}, $values));

// now I can safely inject the values into SQL:
$stmt = $pdo->query("SELECT username FROM userInfoTable WHERE username IN ($in)");

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Exit mobile version