Anda di halaman 1dari 2

Prevent SQL injection vulnerabilities in PHP applications and fix them

Posted on May 9, 2017 by Ian Muscat

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

Warning The following code block contains SQL Injection vulnerabilities


<?php

/*
* Check if the 'id' GET variable is set
* Example - http://localhost/?id=1
*/
if (isset($_GET['id'])){
$id = $_GET['id'];

/* Setup the connection to the database */


$mysqli = new mysqli('localhost', 'dbuser', 'dbpasswd',
'sql_injection_example');
/* Check connection before executing the SQL query */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}

/* SQL query vulnerable to SQL injection */


$sql = "SELECT username
FROM users
WHERE id = $id";

/* Select queries return a result */


if ($result = $mysqli->query($sql)) {
while($obj = $result->fetch_object()){
print($obj->username);
}
}
/* If the database returns an error, print it to screen */
elseif($mysqli->error){
print($mysqli->error);
}
}

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.

http://localhost/?id=-1 UNION SELECT password FROM users where id=1


> $2a$10$SakFH.Eatq3QnknC1j1uo.rjM4KIYn.o8gPb6Y2YBnNNNY.61mR9K

Anda mungkin juga menyukai