Best way to defend against mysql injection and cross site scripting

Just doing a lot of stuff that you don’t really understand, is not going to help you. You need to understand what injection attacks are and exactly how and where you should do what.

In bullet points:

  • Disable magic quotes. They are an inadequate solution, and they confuse matters.
  • Never embed strings directly in SQL. Use bound parameters, or escape (using mysql_real_escape_string).
  • Don’t unescape (eg. stripslashes) when you retrieve data from the database.
  • When you embed strings in html (Eg. when you echo), you should default to escape the string (Using htmlentities with ENT_QUOTES).
  • If you need to embed html-strings in html, you must consider the source of the string. If it’s untrusted, you should pipe it through a filter. strip_tags is in theory what you should use, but it’s flawed; Use HtmlPurifier instead.

See also: What’s the best method for sanitizing user input with PHP?

Leave a Comment