简体   繁体   中英

Is it safe using addslashes in php when parameter charset is utf-8?

I have read many post talk about addslashes is not safe for SQL injection, but they all refer same example using GBK encoding. So my question is: Is it safe using addslashes() to prevent SQL injection in php when parameter charset is utf-8?

In fact, there are two questions in one. And so it's better to voice them separately.

For the question

Is it safe using addslashes() if charset is utf8?

The answer is YES, it is safe.
Taken by itself, with isolated example, addslashes can produce a safe sequence to be used in the SQL string literal if your charset is utf8 .

However, taken as a protection measure, intended, as it is commonly used, to "process all the input data to make it safe" it is proven to be fatally insecure. Which for the question

Is it safe using addslashes() to prevent SQL injection

makes it the only answer:

NO WAY!

Simply because that this honest function has nothing to do with protection from any injections. And never has been.

What you have to understand, is that the main threat is coming not from the semi-mythical GBK vulnerability, but entirely from the misuse of this function. As it's just not intended to protect you from injections. The topic of protection is much more complex than simple string escaping.

The problem is that there are a lot of rules to keep in mind . And there are a lot of points of possible failure.

For these reasons, a simple string escaping just cannot be considered as an all-embracing protection rule.

From this point of view, parametrized queries, although not offering the 100% protection, can be considered a WAY better measure anyway, eliminating three most dangerous threats:

  • because numbers also covered, there is no way to inject via numeric literal
  • because of complete formatting, a wrongly escaped identifier becomes not a breach but a development stage error.
  • because of automated formatting, a human error is eliminated

The above these three reasons I consider enough for changing your approach.

Besides, properly implemented parametrized queries make your code DRAMATICALLY cleaner. Give me your addslashes-based code snippet, and I'll show you how to make it 3-5 times shorter and cleaner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM