How can I safely display user-supplied HTML on my site?

Like eBay or Myspace, I have a section of my site where I let users provide a description in text, and I'd like to allow HTML for fonts, colors, etc. But how, when later displaying this text to another user, do I prevent them from injecting script and other malicious HTML content? Will I have to manually rework their HTML, or is there a browser-level approach like IFRAMING the code, etc?

Public Comments

  1. Make the choices available from text box selection that way only coded choices can be made
  2. You will need to learn a server side language like PHP to do this. I only know PHP. The simple way to disable all HTML codes from PHP is to use htmlentities (source 1) on the user input when saving it. By doing this, you disable the execution of html tags when the code is recalled. However, BBcodes may fit your needs more precisely. You could try to write your own simple one, but I suggest using the PEAR package HTML_BBCodeParser (source 2). If you can't use PHP, look for something similar in whichever server side language your host allows.
  3. The easiest way in my opinion is to think of all the tags which you want your user to be able to use. For example. <p> <h1> <h2> <h3> <div> (but only if there is a closing </div> too.. etc etc. Then you can use a regular expression function to remove all tags which aren't of this type.
Powered by Yahoo! Answers