I am experimenting with PHP and MySQL, but now I found a PHP code that I want to use, but it’s vulnerable for SQL injection. Does anyone know what the injection is and what code can fix it?
<?
// both the username and password must be specified
if(!isset($_GET["username"]) || !isset($_GET["password"])) {
print "NO username and/or password";
die;
}
$username = $_GET["username"];
$password = $_GET["password"];
// prepare database connection
mysql_connect("host", "user", "password");
mysql_select_db("dbase");
// validate the specified username
$res = mysql_query("SELECT id FROM users WHERE username = '$username'");
if(!$res || !($row = mysql_fetch_row($res))) {
print "Unknown username";
die;
}
// validate the password
$res = mysql_query("SELECT password FROM users WHERE id = ".$row[0]);
if(!$res || !($row = mysql_fetch_row($res))) {
print "Illegal userid record";
die;
}
if($password != $row[0]) {
print "Invalid password";
die;
}
// Access Granted
?>
The code is part of an extra code but that one isn’t necessary, the username can be selected with /somecode.php?username=’ OR ‘1’=’1&password=something but ‘ OR doesn’t work with the password, could anyone help me?
Regards
Do not build your SQL code dynamically – pass user input as parameters.
See this example in the PHP documentation.
If you dynamically build your SQL like this:
where
$usernamecould contain something which was directly provided by a user, then you are at risk. Using a solution such as a prepared statement, where it is not possible for a user to directly influence the actual SQL query being executed, is a safer alternative.