Hey there, I’m doing some queries to a MySQL database that involves some user-input.. And I was wondering how to prevent injection attacks, like, for example, if someone were to type
"; a-MySQL query here;"
It would be executed, this would allow people access to compromise my system. I’m wondering how i could protect against things like this, possibly create a function that filters out the query looking for bad statements? or perhaps not allowing the ; character?
To sum it all up:
- Whats the common practice now adays to prevent injection attacks?
- How should I go about it?
- How effective will this solution be against people who know what they are doing from changing my database.
The only way is to properly escape user-submitted data. Others have pointed out some ways of doing so.
There’s another way: prepared statements and placeholders. Prepared statements are supported by every modern PHP database interface, including mysqli and PDO.
Let’s use PDO as a demonstration. Let’s say we wanted to update a bit of data in the table
foosubmitted by a user.The variables in the array passed to
executereplace the question mark placeholders in the query. When this happens, they are automatically escaped and quoted. You don’t need to manually escape them to make them safe to put in the database!On the other hand, you will still need to filter them for unexpected content, like HTML, Javascript, letters where you expect numbers, etc. Making data safe to insert into the database is only half of the battle.