article

Friday, February 22, 2013

Sanitize Data to Prevent SQL Injection Attacks

Sanitize Data to Prevent SQL Injection Attacks
simple function that sanitizes the data before sending it to MySQL




 
function sanitize($data)
{
// remove whitespaces (not a must though)
$data = trim($data); 

// apply stripslashes if magic_quotes_gpc is enabled
if(get_magic_quotes_gpc()) 
{
$data = stripslashes($data); 
}
// a mySQL connection is required before using this function
$data = mysql_real_escape_string($data);
return $data;
}

session_start();
$username = sanitize($_POST['username']);
$password = md5(sanitize($_POST['password']));
$query = sprintf("SELECT * FROM `members` WHERE username='%s' AND password='%s'",$username, $password);
$sql = mysql_query($query);
if(mysql_num_rows($sql))
{
// login OK
$_SESSION['username'] = $username;
}
else
{
$login_error = true;
}

Related Post