Saturday, February 14, 2009

htmlspecialchars()

If you rigoursly validate your HTML like I do, you've probably seen many times the warning about HTML entities. Inevitably an ampersand makes its way into your code without being properly encoded. It's almost always in a hyperlink where you're trying to pass a QueryString variable or two.


somefile.asp?this=that&blah=meh


That ampersand needs to be encoded as &. Likewise, double quotation marks need to be encoded as " and the greater than and less than symbols need to be encoded as > and < respectively. If you allow users to write things on your web site, then you need a programmatic solution. Our PHP programmer friends have one in their toolbox which we can borrow.


  1. function htmlspecialchars(someString)
  2.     ' Critical that ampersand is converted first, since all entities contain them.
  3.     htmlspecialchars = replace(replace(replace(replace(someString, "&", "&"), ">", ">"), "<", "<"), """", """)
  4. end function
  5. function htmlspecialchars_decode(someString)
  6.     htmlspecialchars_decode = replace(replace(replace(replace(someString, "&", "&"), ">", ">"), "<", "<"), """, """")
  7. end function

View ASP implementation on Snipplr

No comments: