Reputation: 25
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?
Upvotes: 1
Views: 1884
Reputation: 157913
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:
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:
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.
Upvotes: 3