Saturday, 15 March 2014

php - How Mysqli_escape_string or Prepared statement can save me from SQL Injection -



php - How Mysqli_escape_string or Prepared statement can save me from SQL Injection -

i reading lots of forums , answers on stack on flow regarding sql-injection

and came know basic level of sql-injection

$_post['name'] = 'xyz;drop table users'; mysqli_query ('select * abc name='."$_post['name']")

to prevent

use mysqli_escape_stirng on input comes user can save me sql-injection use pdo , prepare statement can save me sql-injection

q1. want know here how passing info mysqli_escape_string can save me sql-injection

$safe_variable = mysqli_escape_string($connection ,$_post['name'];

how mysqli_escape_string save "xyz" post info , leave rest of part (if case)

q2. how pdo save me sql-injection

$stmt = $dbh->prepare("select * abc name = :name"); $stmt->bindparam(':name',$name); $name = $_post['name']; $stmt->execute();

any help in regard highly appreciated

q1:

mysql(i)_real_escape_string() calls mysql's library function mysql(i)_real_escape_string, prepends backslashes next characters: \x00, \n, \r, \, ', " , \x1a.

(http://php.net/mysqli_real_escape_string)

note depends on character encoding (not workin in case set names ... (security risk!!!), $mysqli->set_charset('utf8'); should used!). (you can read encoding in post mastering utf-8 encoding in php , mysql.)

how prevent sql injection? - prevents breaking variables context escaping ' etc, thing is, mysql_query , mysqli_query execute one query per query, means, ignores ;drop table users.

mysqli_real_escape_string does not prevent inserting code drop database.

only pdo and/or mysqli_multi_query vulnerable in case.

q2:

the statement sent server first, bound variables sent seperated , statement gets executed, in case, security provided database library, not client library. should prefere this.

that means, first send $dbh->prepare("select * abc name = :name"); server , database knows bind param inserted :name placeholder , automatically wrap not break out of supposed context. database seek name value of xyz;drop table users , won't executed command, fill variable space.

php mysqli prepared-statement sql-injection

No comments:

Post a Comment