1
\$\begingroup\$

I have a class that creates user accounts and to avoid SQL injection attacks, I am using the following functions to sanitize both the user name and password inputs:

    $admUsername = filter_var($_POST['admUsername'], FILTER_SANITIZE_STRING);
    $admPassword = filter_var($_POST['admPassword'], FILTER_SANITIZE_STRING);

    $s->bindParam(':admUsername', $admUsername, PDO::PARAM_STR);
    $s->bindParam(':admPassword', $admPassword, PDO::PARAM_STR);

But since I am using filter_var(), when a user creates an account or tries to login, all the special characters like (?,/.!() that s/he inputs are removed. For that reason only alphanumeric characters can be used for the passwords, which might not always be good for the user's security. So my question is, if I use bindParam, is it necessary to also use filter_var or will bindParam do the work that filter_var does?

| improve this question | | | | |
\$\endgroup\$
  • \$\begingroup\$ I have no experience in php but it doesn't seem as overkill to do it, the more protection the better. Unless of course both functions do the same or one of them is very expensive. \$\endgroup\$ – Machinarius Jun 25 '15 at 11:58
  • \$\begingroup\$ It's overkill - bindParam sanitises input for the database anyway. Technically you'd be fine with $s->bindParam(':admUsername', $_POST['admUsername'], PDO::PARAM_STR); ... I'm not saying don't use filter_var, just not for this. See : stackoverflow.com/questions/60174/… \$\endgroup\$ – CD001 Jun 25 '15 at 15:35
2
\$\begingroup\$

Prepared statements (which you use, as you use bindParam) are the correct way to prevent SQL injection.

It is still recommended - but not necessary - to clean input parameters with filter_var, but just as a second (or in this case first) line of defense.

What if you forget to prepare that variable somewhere? Maybe when you retrieve it from the db and use it in a second query? Or what if you echo it somewhere and forget to use proper encoding?

No program is 100% secure, so if you know that you never want special characters in your usernames, then it's a good idea to filter. If you do want those characters, then don't filter.

all the special characters like (?,/.!() that s/he inputs are removed.

No, they are not. All those characters pass FILTER_SANITIZE_STRING without a problem. It only strips tags and encodes some chars (single and double quotes). The documentation is not very clear on what tags are, but generally it's something like <.*>, although the filter also removes <bar from foo<bar, so you could get problems if you want to allow the < character.

| improve this answer | | | | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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