Blog > detail

Just my tiny mind

Avoid MySql Injection

26-2-2012 Admin General 2 Comments

Avoid MySql Injection

Before we can Avoid MySql Injection, we have to know what is MySql Injection. MySql  Injection is an action performed by system user to make harm to the Database system. User will input MySql statement into an input tag that most of the tag type is text. However there is a browser that can manipulate the HTML element that will make more easier to connduct MySql Injection. On the other hand, MySql Injection can be conducted by using variable get from url.


Exp you have code:


$search = $_GET['search'];

$query = "Select * from `member` where `username` = '".$search."'";

//if user input just a simply name then it will be ok $search = septiadi

$search ="Select * from `member` where `username` = 'septiadi' "; //this will be ok

//if user input nasty statement $search = ' or '1' = '1

$search ="Select * from `member` where `username` = '' or '1' = '1' "; //this will be bad


If the user input " ' or '1' = '1' "  the statement will always true. If you use it for authentication process, you will gain access easily. On a very extreme condition, user may give statement  to delete table or drop database. Such as " '; DROP TABLE `member` where  '1' = '1".


To Avoid MySql Injection, we simply add a function for every input from user in our PHP files. Exp:


$search = mysql_real_escape_string($_GET['search']);//for PHP 4.3.0 and above

//if magic_quotes_gpc is enabled, first apply stripslashes() to $search

$query = "Select * from `member` where `username` = '".$search."'";


For you that use ajax or jquery, I recomend that you put all of the executing code into one PHP file. In this case, it will be easier to implement mysql_real_escape_string to Avoid MySql Injection. I'll give an aditional function that automaticlally implement mysql_real_escape_string to any input.


function clean_query($query){

if(get_magic_quotes_gpc()){

$result = stripslashes($query);

}

else {

$result = $query;

}

$result = mysql_real_escape_string($result);

return $result;

}

/* the above function is to avoid MySql injection */

foreach($_POST as $key => $val){

$_POST[$key] = clean_query($_POST[$key]);// change all $_POST with clean_query function

}


Place the above code into the frist line of your PHP file. It will replace all $_POST with $_POST that has been implemented by mysql_real_escape_string to Avoid MySql Injection. You can change $_POST into $_GET based on your coding.


MySql Injection is quiet simple but indeed very dangerous. Therefore, Avoid MySql Injection is an absolute needs for web developer that use database.


 


Avoid MySql Injection Avoid MySql Injection Avoid MySql Injection

Avoid MySql Injection Avoid MySql Injection Avoid MySql Injection

Avoid <a href=MySql Injection" width="1" height="1" />

word word

Avoid MySql Injection

Avoid MySql Injection

Avoid MySql Injection