Prevent SQL Injection
Prevent SQL Injection
SQL injection (SQLi) refers to an injection attack wherein an attacker can execute arbitrary
SQL statements by tricking a web application in processing an attackers input as part of an
SQL statement. This post will focus on how to prevent SQL injection vulnerabilities within
PHP applications and fix them.
This post assumes you have a basic understanding of SQL injection and the different
variations of SQL injection.
The problem
Before we delve into how to prevent SQL injection in PHP, we need to understand what an
application vulnerable to SQL injection looks like. In this example, well be using a very
simple application which accepts an id inside of a GET parameter (this can very well be a
POST request or any other HTTP method) and prints the name of a user on screen.
Note This example shall be using MySQL, however, the same principles apply for other databases
Our simple application will have a database with the following table called users.
i first_na last_na
username password
d me me
$2a$10$SakFH.Eatq3QnknC1j1uo.rjM4KIYn.o8gPb6Y2YBnNNNY.6
1 johnsmith John Smith
1mR9K
maryjohns $2a$10$hA/hwCzhr6F23BsbRZBjdOA5eqTgV01cv30sy/O2EcL2/zG
2 Mary Johnson
on 9k0aGy
jameswillia $2a$10$OkV5tCMMsy91pkkMXHa94OgcunNtuhxsQcxaOW6tJim
3 James Williams
ms uaCO0FMDZm
$2a$10$2NgAjstT9NcN58zMcF/Rq.pYt5bg3iQ6OmdRgR3YWfT.ZV
4 lindabrown Linda Brown
gmJR4FK
/*
* Check if the 'id' GET variable is set
* Example - http://localhost/?id=1
*/
if (isset($_GET['id'])){
$id = $_GET['id'];
The following is an example of a legitimate HTTP request that could be made to the
vulnerable application above.
http://localhost/?id=1
> johnsmith
The following is an example of a malicious HTTP request that could be made to the
vulnerable application above.