允许用户提供的<iframe>而不会有XSS的风险?

My website is allowing blogging , i use textarea for the blog post and i need to allow the users to share things like youtube videos (i will need to allow iframe tag to do so) or display images using the img tag or using links by allowing the a tag , The problem is i need to secure the website against XXS attacks and that is why i am afraid to allow those tags, is there any work around to accomplish this ?

can i use something like this :

<?php
   $string = "<b>hello world!</b>";
   echo "without filtering:".$string;
   echo "<br>";
   $filtered = htmlspecialchars($string); // insert into database filtered
   echo "After filtering:".$filtered;
   echo "<br>";
   $de_filtering = htmlspecialchars_decode($filtered); //retrieve from database and display
   echo "After de-filtering:".$de_filtering;        
  ?>

is it possible to do that ?

The freshly released HTMPurifier 4.4 adds a feature for doing exactly this.

http://htmlpurifier.org/phorum/read.php?5,5319,5555#msg-5555

In short, you should allow iframes that come from trusted domains. Iframes from untrusted domains could include malicious javascript/flash/embeds

I would very much recommend using a pre-built rich text editor. Building your own will be a long process, and can be very cumbersome. TinyMCE (Under a GPL license) is a very popular one, and so is CKEditor (though this one costs money). There are many more out there, but I would definitely recommend using an existing one instead of building your own.

As for preventing some XSS attacks, you can look at a couple different locations for information regarding XSS. Some good basic things are always sanitize everything and always assume that something has been hijacked. Don't trust input from a user until you have verified it is what you expect.