PHP Programming - SQL Injection Attacks
PHP Programming - SQL Injection Attacks
0.1
1 Use of mysql_real_escape_string()
The Problem
The query selects all rows from the users table where the
username is equal to the one put in the query string. If
you look carefully, you'll realise that the statement is vulnerable to SQL Injection - quotes in $_GET['username']
are not escaped, and thus will be concatenated as part of
the statement, which can allow malicious behaviour.
Consider what would happen if $_GET['username'] was
the following: " OR 1 OR username = " (a double-quote,
followed by a textual " OR 1 OR username = " followed by
another double-quote). When concatenated into the original expression, you have a query that looks like this: SELECT * FROM users WHERE username = "" OR 1 OR
username = "". The seemingly redundant OR username
= " part added is to ensure that the SQL statement evaluates without error. Otherwise, a hanging double quote
would be left at the end of the statement.
0.2
The Solution
Never trust user provided data, process this data only after validation; as a rule, this is done by pattern matching.
In the example below, the username is restricted to alphanumerical chars plus underscore and to a length between eight and 20 chars - modify as needed.
if (preg_match("/^\w{8,20}$/", $_GET['username'],
$matches)) $result = mysql_query(SELECT * FROM
users WHERE username=$matches[0]"); else // we
don't bother querying the database echo username not
accepted";
References
5.1
Text
5.2
Images
5.3
Content license