Jumat, 21 Agustus 2009

Using Mysql Escape String to Prevent SQL Injection

mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.

This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.

Example SQL Injection


// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'picas';
$_POST['password'] = "' OR ''='";

// This means the query sent to MySQL would be:
echo $query;


The query sent to MySQL:

SELECT * FROM users WHERE user='picas' AND password='' OR ''=''

This would allow anyone to log in without a valid password.


example in use :

$idseal = mysqli_real_escape_string($link, $_GET[id]);
$sql = "select s.id, s.nama, j.namajabatan, s.foto, s.flag from tb_staff s, m_jabatan j where s.jabatan=j.idjabatan and id=$idseal order by s.id";

echo"$sql";


Some string Injection will be add triple slash like image follow :


With this manner we can prevent SQL Injection

Related Post:

Tidak ada komentar: