In the previous article, we have discussed about What is SQL Injection. Now here we will discuss, How to prevent from SQL Injection in php?
Why an SQL Injection Occurs?
SQL injection risks occurs every time when a programmer creates a dynamic database query, which contains user input. This means that the ways to prevent an SQL injection are two:
- Don’t write dynamic database queries
- Don’t allow user input in your queries.
You should validate all input to your applications for type, length, format, and range. By constraining the input used in your data access queries, you can protect your application from SQL injection. With some coding techniques applicable in any programming language, SQL injections can be prevented. Use regular expressions to reject any characters that are not on the list.
To protect your application from SQL injection, perform the following steps:
Primary Defenses:
- Step #1: Use of Prepared Statements (Parameterized Queries)
Language specific recommendations:
- Java EE – use PreparedStatement() with bind variables
- .NET – use parameterized queries like SqlCommand() or OleDbCommand() with bind variables
- PHP – use PDO with strongly typed parameterized queries (using bindParam())
- Hibernate – use createQuery() with bind variables (called named parameters in Hibernate)
- SQLite – use sqlite3_prepare() to create a statement object
- Step #2: Use of Stored Procedures
- Step #3: Escaping all User Supplied Input
Additional Defenses:
- Also Enforce: Least Privilege
- Also Perform: White List Input Validation
There are the three types of SQL Injection Attack :-
Don’t use string (like http://www.target.com/index.asp?id=123) because a Havij or SQL Fever tool will easily hack it like below image-
Just use 10 steps that can protect your website from SQL injection :-
Very great post. I just stumbled upon your blog and wished to say that I’ve truly loved browsing your weblog posts. In any case I抣l be subscribing on your feed and I hope you write once more soon!