SQL Injection in PHP

Most common web application vulnerability is SQL injection, an attack very similar to XSS. The difference is that SQL injection vulnerabilities exist wherever you use un-escaped data in an SQL query

The following example demonstrates an SQL injection vulnerability

$hash = hash($_POST['password']);
$sql = "SELECT count(*) FROM users
 WHERE username = '{$_POST['username']}' AND password = '{$hash}'";
$result = mysql_query($sql);

The problem is that without escaping the username, its value can manipulate the format of the SQL query. Because this particular vulnerability is so common, many attackers try usernames such as the following when trying to log in to a target site:

chris’ —

because it allows access to the account with the username chris’ without me having to know that account’s password. After interpolation, the SQL query becomes:

SELECT count(*)
FROM users
WHERE username = ‘chris’ –‘
AND password = ‘…'”;

Because two consecutive hyphens (–) indicate the beginning of an SQL comment, this query is identical to:

SELECT count(*)
FROM users
WHERE username = ‘chris’

Safeguarding your applications against SQL injection is primarily accomplished by escaping output:

$mysql = array();
$hash = hash($_POST[‘password’]);
$mysql[‘username’] = mysql_real_escape_string($clean[‘username’]);
$sql = “SELECT count(*) FROM users
WHERE username = ‘{$mysql[‘username’]}’ AND password = ‘{$hash}'”;
$result = mysql_query($sql);

Leave a Comment