php-development-services

Avoid SQL injections (PHP code)

SQL injection is a major security fault, in which hackers try to manipulate data sent by the browser to the server, and inject SQL queries with it.

A simple example can be:

$UserInput = $_GET(“id”);
$SQL = “SELECT * FROM Users WHERE UserId = ” .UserInput;

In that example, the code is reading a GET input field from the user, and adding it to the SQL query. he user could inject something like “5; DELETE * FROM Users;” which will delete all the Users table database.

To get around it, as a developer, you need to filter all input coming from the user. The following PHP function can do that for you:

function cleanse_rubbish($array_to_cleanse)
{
$cleansed_array=array();
$values_of_array=array();

$num=count($array_to_cleanse);
$keys_of_array=array_keys($array_to_cleanse);
$values_of_array=array_values($array_to_cleanse);
for ($i=0; $i<$num; $i++)
{
$values_of_array[$i]=str_replace(“‘”,””,$values_of_array[$i]);
$values_of_array[$i]=str_replace(“DELETE”,””,$values_of_array[$i]);
$values_of_array[$i]=str_replace(“SELECT”,””,$values_of_array[$i]);
$values_of_array[$i]=str_replace(“INSERT”,””,$values_of_array[$i]);
$values_of_array[$i]=str_replace(“JOIN”,””,$values_of_array[$i]);
$values_of_array[$i]=str_replace(“<script”,”script”,$values_of_array[$i]);
$values_of_array[$i]=str_replace(‘”‘,””,$values_of_array[$i]);
//$values_of_array[$i]=str_replace(“&”,””,$values_of_array[$i]);
$cleansed_array[$keys_of_array[$i]]=strip_tags(html_entity_decode($values_of_array[$i]));
}

return $cleansed_array;
}

And now, in the beginning of your code, you should cleanse all the $_GET (and $_POST) input:

$cleansed_get = cleanse_rubbish($_GET);
$cleansed_post = cleanse_rubbish($_POST);

and instead of using $_GET as an array, just use $cleansed_get (and same for $_POST and $cleansed_post).

Good luck!

Comments

comments

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *