Development

PHP MySQL injection; What, how and avoid

MySQL injection is the method in which “hackers” can get unauthorized data or inject it. Good news is that its easy to fix, bad news is that PHP code with MySQL vulnerability is as common as the sun coming up each morning.

The basis of a vulnerability occurring is when the input is not escaped. Take this for an example the page users.php?id=

 

users.php?id=44 the $sql would be : SELECT * FROM user_data WHERE id = 44

and the page would display our data for user id 44.

But what happens if someone did users.php?id=44%20or%201=1 (%20 is a URL encoded space) that would leave you open to this SELECT * FROM user_data WHERE id = 44 or 1=1 This is going to return all results. Bad bad news.

The motivation against all MySQL injections is the same, prevent the use of AND or OR by escaping the input this is done by mysqli_real_escape_string

$sql = "SELECT * FROM user_data WHERE id = '".mysqli_real_escape_string($id, $connection)."'";

Now makes an attempted injection: SELECT * FROM user_data WHERE id = '44 or 1=1' which sadly for the injector isn't valid MySQL and wont return any rows.

Another method to avoid potential injections with PHP and MySQL is to use PDO, I wrote a post here and provided examples. You end up needing more code but you get security which is always crucial.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago