How can I use HTMLPurifier to filter xss but also to allow iframe Vimeo and Youtube video?
require_once 'htmlpurifier/library/HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.Trusted', true);
$config->set('Filter.YouTube', true);
$config->set('HTML.DefinitionID', '1');
$config->set('HTML.SafeObject', 'true');
$config->set('Output.FlashCompat', 'true');
$config->set('HTML.FlashAllowFullScreen', 'true');
$purifier = new HTMLPurifier($config);
$temp = $purifier->purify($temp);
HTMLPurifier version 4.4.0 has new configuration directives to allow YouTube and Vimeo iframes:
//allow iframes from trusted sources
$cfg->set('HTML.SafeIframe', true);
$cfg->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/)%'); //allow YouTube and Vimeo
For anyone who is struggling (how to enable iframe and allowfullscreen)
$config = \HTMLPurifier_Config::createDefault();
$config->set('HTML.SafeIframe', true);
$config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/)%'); //allow YouTube and Vimeo
// This line is important allow iframe in allowed elements or it will not work
$config->set('HTML.AllowedElements', array('iframe'));// <-- IMPORTANT
$config->set('HTML.AllowedAttributes','iframe@src,iframe@allowfullscreen');
$def = $config->getHTMLDefinition(true);
$def->addAttribute('iframe', 'allowfullscreen', 'Bool');
$purifier = new \HTMLPurifier($config);
$purifiedHtml = $purifier->purify($html);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With