I've design this small function and I would like to know if anyone thinks it's safe enough, or if not, why.

    function safeSQLI($INPUT){
      // Trim un-needed spaces
      $safe_input = trim($INPUT);

      // Replace any SQL commands
      $safe_input = str_ireplace("drop",    "", $safe_input);
      etc...

      // Escape the result
      $safe_input = mysql_real_escape_string($safe_input);

      // Return the "Safe" result
      return $safe_input;
}

Answer: No, it's not safe at all. I am now using PDO and I think I was missing something great before now.

有帮助吗?

解决方案

str_ireplace() is generally a bad choice, because it doesn't work recursive. Try the following:

$safe_input = 'DELDELETEETE * FROM users';

Will result in:

DELETE * FROM users

So, your entire function falls back to mysql_real_escape_string() and everything that came before is useless. The point is: It's not impossible to write proper filtering methods, but it can be a real challenge to cover every single case there is.

You want to either follow a whitelisting approach and allow only certain types of content. This is tough to implement in the real world.

Or a blacklisting approach and deny certain characters. Most SQL injection vulnerabilites happen because one can inject additional commands in a string. If you escape the ' (or use mysql_real_escape_string(), you are usually safe). However, it depends on your web app if additional filtering is required or not.

Or use prepared statements.

其他提示

It does prevent injection, provided you use quotes like you should:

SELECT * FROM `users` WHERE `name`='$username'

For example.

However it is complete overkill. mysql_real_escape_string is sufficient to make an input safe, provided you use the quotes as above.

I spent all day today trying to get some database work done on a server that had been locked down to return "Not Acceptable" HTTP responses if "anything that looked like a database table name was present in the request". Needless to say, it took significantly longer than it needed to, when a simple mysql_real_escape_string would have sufficed.

Not safe at all. Try running this:

 echo safeSQLI("drdropop tatableble TABLE_NAME");

That never let you insert a post about SQL in your blog.

I think use prepare statements and mysql_real_escape_string is safe enough.

PS: And you can avoid DDL sentences at BD level, with permissions.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top