Preventing SQL Injection

Post Reply
User avatar
Shane
Captain
Captain
Posts: 226
Joined: Sun Jul 19, 2009 9:59 pm
Location: Jönköping, Sweden

Preventing SQL Injection

Post by Shane » Fri Sep 04, 2009 2:57 am

Most important point here to prevent SQL injection is verify user input data.
Use of a regular expression to match each data before processing can help.

To limit text to A-Z or a-z or 0-9 or _ characters, use following method.

Code: Select all

 $pattern    = '/^[a-zA-Z0-9]+$/'; 
 echo preg_match($pattern,'Expertcore');
 
This code will return 1 if the text is passed or else return 0. If it is zero then avoid processing data.
Similarly, if waiting for a $_GET based Record ID which needs to have only numbers, following method can be used.

Code: Select all

 $pattern    = '/^[0-9]+$/'; 
 echo preg_match($pattern,'453');  
 
In this was we can easily overcome with the SQL Injection attack.
Post Reply

Return to “PHP & MySQL”