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)

for ($i=0; $i<$num; $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!



One comment

Leave a Reply

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