Is filter_var() sufficient to avoid SQL Injection?

Asked

Viewed 714 times

4

Handling input variables in a Mysql query using filter_var is sufficient to avoid Injection?

  • 1

    Making data files also helps, and something else would be a methods to check if you have or and in the strings.

3 answers

5

Not filter_var() is useful for making some types of validations such as

  • Is empty?
  • Is numerical?
  • Is it an IP? (among others)

To avoid sql injectction use the function mysqli_real_escape() if you are using the class mysqli

Or use Prepared statements if you’re using the PDO class

  • It does not only validate. Depends on use. It can be validation or "cleaning". I just don’t know if cleaning is enough. But using mysqli_real_escape is good tip, even.

  • can use Prepared statements with mysqli as well. In mysqli, Prepared statements are native, in PDO by default they are only simulated on the client side with string concatenation, which in addition to lowering performance, eliminates the reason that prepareds statements exist, which is the reuse.

4


No. The filter_var is intended to validate and filter fields. Its main goal is not to prevent specific SQL Injection attacks, but only to sanitize data.

Of course, for some cases it can actually be useful for you to validate and filter data that will be used in your query.

For example:

 $id = filter_var($_GET['id'], FILTER_VALIDATE_INT);

 $id === false && die("O valor do ID não é válido");

 $sql = "SELECT * FROM usuarios WHERE id = {$id}"

I believe that the Prepared statments PDO can be a good solution to decrease the risks of you leaving your code vulnerable.

In my case, I prefer to use libraries that work with database data (such as Doctrine, Eloquent, Readben), since in their development there is a concern not to allow this type of attack.

Another thing is not to trust the good intention of the user. If your code is misspelled it can also be a problem that will not be solved nor with data sanitization functions.

I won’t say much because I think we already have good content here on the site referring to "avoid this attack".

Links:

-2

I use a super basic function that simply takes the ' (apostrophe) and replaces it with two apostrophes (''), and takes the (backslash) and replaces it with . So there’s no way there’s any Injection.

  • 2

    I think it’s cool you want to help by sharing your experience, but in the specific case, your solution is completely wrong and your codes remain vulnerable. I suggest learning to protect the code using the correct path, which are the proper functions of the interface with DB. Here is a starting point: http://answall.com/questions/3864/70

  • http://stackoverflow.com/a/31726442/540552

Browser other questions tagged

You are not signed in. Login or sign up in order to post.