This tutorial will help you protect and prevent your website from being hacked. One way hackers can gain access to your site is using SQL injection. It works when you have exposed MySQL variable in your website address, for example you have a page on your website containing this kind of link (mypage.php?ID=34). We all knew that the basic mySQL query for this code is “SELECT * FROM `table` WHERE `id` = “.$_GET[‘ID’]” and mostly developers forgot to protect this code from possible SQL injection. How the hackers attacked it? They simply alter the path of your site to (mypage.php?ID=34 union(Some malicious SQL queries)) then BOOM! they can now see the tables from your database and gaining access from it.
In order to prevent it from happening, we need to add some enhancement and an improved to our SQL codes. Some of these are the following:
Adding addslashes() for every variable in your SQL query string, this will return a string with a backslash and prevent unwanted SQL queries in your variable.
$id = addslashes($_GET[‘id’]);
$query = “SELECT * FROM `table` WHERE `id` = $id”;
Another is is_numeric(), if your variable is purely integer, you can simply used this code to verify if the query string variable is integer or an string SQL injection.
$query = “SELECT * FROM `table` WHERE `id` = “.$_GET[‘id’];
The most effective way is using sprintf(), this will ensure that the variable is treated the way it supposed to be treated. For example we use %d for integer, we use %s for string and etc..
$id = $_GET[‘id’];
$query = sprintf(“SELECT * FROM `table` where `id` = ‘%d'”,$id);
Lastly, updating your server software to latest apache, mySQL, and PHP version will also prevent from this vulnerability. These are just some ways to prevent your site from SQL injection attacked.
Hope this help!