Categories: 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…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago