1
function addUser($username, $first_name, $last_name, $email, $pw, $type) {
include $_SERVER['DOCUMENT_ROOT'] . '/connection_library/connection_library.php';
$insertRow = NULL;
$connection = connectUserLogfiles();
try {
    $sql = "INSERT INTO user_list (username, first_name, last_name, email, password, type) "
            . "VALUES (:username, :first_name, :last_name, :email, :pw, :type)";
    $stmt = $connection->prepare($sql);
    $stmt->bindParam(':username', $username, PDO::PARAM_STR);
    $stmt->bindParam(':first_name', $first_name, PDO::PARAM_STR);
    $stmt->bindParam(':last_name', $last_name, PDO::PARAM_STR);
    $stmt->bindParam(':email', $email, PDO::PARAM_STR);
    $stmt->bindParam(':pw', $pw, PDO::PARAM_STR);
    $stmt->bindParam(':type', $type, PDO::PARAM_STR);
    $worked = $stmt->execute();
    $stmt->rowCount();
    $stmt->closeCursor();
} catch (Exception $ex) {
    return FALSE;
}
return $worked;
}

I have heard that using bindParam will prevent SQL injection attacks. Is this true? Is there a way to execute SQL injection attacks on this code? Assuming I perform no filtering or sanitizing on the parameters (with the exception being the password, which has been encrypted with a strong one way encryption scheme), how would you perform a SQL injection attack?

The database is a MySQL database, and the user being used in the connectionUserLogfiles() function only has SELECT, INSERT and UPDATE privileges.

halfer
  • 19,824
  • 17
  • 99
  • 186
Kyle Birch
  • 75
  • 1
  • 10
  • 2
    As long as you use parameterized queries (like you do), have disabled the emulate prepares option (PDO silently falls back to escaping parameters if running on old software), and use UTF-8 (UTF-7 might give you problems), you are good. For a shorter code you could try using unnamed placeholders (?) and just sending in an array of values into the execute function. – JimL Feb 21 '15 at 09:17
  • 1
    I don't mind the slightly longer code because it makes it easier to understand at-a-glance. IMO: readability > length – Kyle Birch Feb 21 '15 at 09:20
  • Yup. Looks perfectly fine to me. Assuming that that `$pw` is a decently salted/hashed password (e.g. using `password_hash()`), there's nothing to ring alarm bells there. – Matt Gibson Feb 21 '15 at 09:40
  • $pw uses MD5 and SHA-512 with a pseudorandomly generated salt, but I don't use password_hash(), I use crypt(). – Kyle Birch Feb 21 '15 at 16:47
  • Use `password_hash()`. You'll be happier that you did. – Scott Arciszewski Oct 04 '18 at 05:53

1 Answers1

0

I have heard that using bindParam will prevent SQL injection attacks. Is this true?

Yes, provided that you disable emulated prepares (they're enabled by default) and your database driver isn't stupid.

Scott Arciszewski
  • 33,610
  • 16
  • 89
  • 206