PHP – Filter Data to Prevent MySQL Injection Attacks

I have created a data filter function to prevent SQL Injection. This function will filter all the parameters before adding into the MySQL.

This function escapes all the characters with slashes like single quotes and double quotes (\’ ‘\ and \” “\).

You can use this solution to prevent from any hacker attacks.

Demo – Hacker attack on your website using the SQL Injection

http://www.testsite.com/emp.php?emp_id=1

Database Connection:

$link = mysqli_connect("localhost", "my_user", "my_password", "emp");

Normal MySQL Query:

$query = "select emp_name from emp where emp_id=".$_GET['id'];

Secure MySQL Query:

$query = "select emp_name from emp where emp_id=".my_data_filter($_GET['id']);

Data Filter Function:

function my_data_filter($data){
    // Remove whitespaces from both sides
    $data = trim($data);
    
    // If magic quotes are enabled
    if(get_magic_quotes_gpc()){
        $data = stripslashes($data); // Un-quotes a quoted string
    }
    
    $data = mysqli_real_escape_string($con,$data); // Escapes special characters in a string for use in a SQL statement
    return $data;
}

trim() function will removes whitespaces from the string.

You must use this function to make secure website.

Leave a Reply

Your email address will not be published.

*