I have addslashes(htmlentities($userInput)). It gets inserted into my database. (NOT a mysql db) Is it sufficiently safe from xss? Thank you!
Asked
Active
Viewed 3,083 times
1
1 Answers
3
What is addslashes for? It has no benefit against HTML injection as it does not remove the characters that are special to HTML.
If it is meant as a protection against SQL injection it is ineffective, especially for non-MySQL databases that don't even use backslash as an escape in SQL string literals. You should exclusively use parameterised queries to get data into SQL queries without SQL injection problems.
htmlentities is OK against injection into HTML text content and double-quoted attribute values. But:
- it doesn't escape
'so it will fail for single-quoted attribute values (add flags parameterENT_QUOTESto fix) - it assumes ISO-8859-1 character set so you will get broken output if you are actually dealing with something else like UTF-8 (add charset parameter to fix, or, probably simpler, use
htmlspecialcharswhich leaves non-ASCII characters alone) - HTML escaping is something you do when you are creating an HTML page. You need to
htmlspecialchars()every piece of text as you drop into HTML because that's the point at which you know that the text needs escaping. Don't HTML escape input between receiving it and writing it to the database, this is completely the wrong time.
bobince
- 12,694
- 1
- 28
- 42
ENT_QUOTESand"UTF-8". What problems may occur by escaping before writing to db? (Which is just a text file at the moment.) – Sep 16 '14 at 20:04