I'm just discovering PHPs sanitize and Validate filters, and I had been using MySQL's mysql_escape_string to stop SQL Injection.
Now I discover that PHP can also help and I guess logically these procedures are not exclusive in their function: ie you can sanitize and validate in PHP and still arrive at a situation where escaping is necessary.
Am I right or am I ov开发者_StackOverflow中文版erlooking something?
Am I right or am I overlooking something?
Nope, you're totally right. Big font incoming for the casual readers that might somehow miss the point of your question.
Different types of output require different types of protection.
Nuke things that could be HTML, and you'll be safer against XSS. Properly quote and escape your database input, and you'll be safer against SQL Injection. Watch for unexpected input everywhere and you will increase the safety of your code.
It is a wonderful thing that you now fully realize this. Too many people don't.
I'm just discovering PHPs sanitize and Validate filters
These are nice, aren't they? They're a good part of modern PHP. Use them religiously and they will not fail you. Except for the email one, it fails a large number of edge-ish cases; I prefer is_email.
I had been using MySQL's mysql_escape_string to stop SQL Injection.
This is ... not a good part of modern PHP. I also hope you're using the escape string function with the word "real" in it, otherwise you may be in trouble.
I think you are ready for the next step: Learn PDO. It has prepared statements and query placeholders, which will provide you free and complete protection against SQL Injection, when you use it properly. PDO is available anywhere that modern PHP versions are available. It's built right in. Use it, learn it, love it. Or else you are doomed. Doomed!
I would advise you to escape every single bit of data you insert into a query with the appropriate encoding-aware function or method your database extension provides. For mysql_
this would be mysql_real_escape_string
(don't forget the real_
part!).
The reasoning is simple: Code evolves. It may often happen, that restrictions for a value are loosened. Imagine you allowed only alphanumeric characters for names before and now you want to allow all Unicode characters. Thus now '
is allowed in names two. But too bad you didn't have that mysql_real_escape_string
in your code, because you thought the name were safe. Well, now it's too late, the private user data was read and now circulates on the black market...
精彩评论