Is this authentication mechanism vulnerable to SQL injection? If so, how could one exploit it, and what is the most effective way to mitigate this?

if (isset($_POST['userid']) && isset($_POST['password'])){

$username = $_POST['userid'];
$password = crypt($_POST['password'],'34l5kj');

    $query = "SELECT * FROM users WHERE name =:username and pass=:password";
$db->bind(':username', $username);
$db->bind(':password', $password);
$data = $db->single();

            $_SESSION['valid_user'] = $username;
            $_SESSION['user_id'] = $data['id'];

You are using bound params which is a great start. This tiny snippet of code should be fine against regular input SQLi but there are a few other potential issues:

  • You are not validating/sanitising the input. Although your are using bind, you should still be doing this
  • You are assigning the password to a session variable. Why? You effectively have the plain text PW floating around your web app
  • You are not sanitising the DB output before storing it in the SESSION variables. Not knowing what your other code looks it is impossible to see how this would be exploited. Just don't take the chance.
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.