开发者

How php/mysqli ( prepared statements + bind params ) protect against SQL Injection?

开发者 https://www.devze.com 2023-04-09 10:26 出处:网络
How php/mysqli ( with prepared statements + bind params ) protect against SQL Injection ? Mysqli applies only \"real_escape_string\" for variables or do something else?

How php/mysqli ( with prepared statements + bind params ) protect against SQL Injection ? Mysqli applies only "real_escape_string" for variables or do something else?

May i say that the function below is totally useless when using mysqli + prepared statements + bind params ?

function no_injection ( $data ) {
$data = trim(strip_tags($data)); // no htm in this case.
$data = get_magic_quotes_gpc() == 0 ? addslashes($开发者_开发技巧data) : $data; // useless.
$data = preg_replace("@(--|\#|;)@s", """, $data); // <--- USELESS ?
return $data;
}

Thanks


addslashes() is NOT unicode aware. There's a fair number of unicode sequences that look like normal text, but turn into different things when processed by non-unicode aware code, allowing a malicious user to construct a "valid" unicode string that comes an SQL injection attack once addslashes trashes the string.

The same goes for your regex. You've not enabled unicode mode, so it can potentially allow malicious unicode characters to leak through and become regular iso8859 chars that'll break the query.

Beyond that, each database has its own escaping requirements. MySQL understands and honors the backslash for escaping, so ' becomes \'. But another database might use '' as the escaped ', and applying a MySQL escape sequence for that database will be useless.

Prepared statements allow a complete separation of query and data. When you write your own query manually, the DB server has absolutely no way of knowing that a part of the query string is potentially malicious and treat it specially. It just sees a query string.

With prepared statements, the query body and the data going into the query are kept separate up until they reach the database server, and the db server can handle the escaping itself.

In real world terms, it's the difference between handing someone a loaf of poisoned bread, and handing them a basket of milk, eggs, flour, bottle of poison, yeast, etc... There's no way to tell there's poison in the bread until after you've eaten it and drop dead. While with the ingredients (aka prepared statement), the DB server will see that bottle of poison and know how to handle it.


It also caches the queries which will increase performance with more "calls".

-> http://dev.mysql.com/doc/refman/5.1/en/c-api-prepared-statements.html -> Should I use prepared statements for MySQL in PHP PERFORMANCE-WISE?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号