Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
870 views
in Technique[技术] by (71.8m points)

php - Sql Injection protection with only str_replace

I'm studying SQL injection and tried in my PHP code this query:

$condition = str_replace(["'",""],["\'",""], @$_GET['q']);
$query = "SELECT * FROM dummy_table WHERE dummy_column = '$condition'";

DB and tables charset is set to UTF8.

I can't inject anything, can someone help me please?

EDIT: As pointed out by GarethD this would escape first ' and than , allowing injection, what about this str_replace?

$condition = str_replace(["","'"],["","\'"], @$_GET['q']);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This isolated example is invulnerable to injection.

But you have to realize that protection from sql injection is not just a character replace. And circumstances may differ from ones you are taking at the moment for granted. So, your code would become vulnerable on the long run, due to essential drawbacks of this method:

  • character replace is only a part of required formatting
  • this particular replacement can be applied to strings only, leaving other parts absolutely unprotected.
  • such a replace is external to a query execution, means it is prone to a human error of any sort.
  • such a replace is an essentially detachable measure, means it can be moved too far away from the actual query execution and eventually forgotten.
  • this kind of escaping is prone to encoding attack, making solution too limited in use.

There is nothing wrong in character replacement per se, but only if it is used as a part of complete formatting; applied to the right query part; and done by a database driver, not a programmer; right before execution.


Functions you proposed in the comments are a good step, but still insufficient, being subjects of the drawbacks listed above, making them prone to all sorts of human errors.

And SQL injection is not the only problem with this approach, it is a usability fault as well, as this function would either spoil your data, if used as an incarnation of late magic quotes, or make your code bloated, if used to format every variable right in the application code.

Such functions can be used only to process a placeholder, but of course not by means of using a homebrewed replace function, but a proper function provided by database API.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...