Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
//add rel="nofollow" and target="_blank" to links with htmlpurifier 4.1.1
require_once '../../library/HTMLPurifier.auto.php';
class HTMLPurifier_AttrTransform_AValidator extends HTMLPurifier_AttrTransform
{
var $name = 'Link validation';
function transform($attr, $config, $context) {
$attr['target'] = '_blank';
$attr['rel'] = 'nofollow';
return $attr;
}
}
$config = HTMLPurifier_Config::createDefault();
// configuration goes here:
$config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
//let them use basic html
$config->set('HTML.AllowedElements', array('br', 'em', 'i', 'b', 'strong', 'strike', 'sub', 'sup', 'a'));
//href is the only one allowed
$config->set('HTML.AllowedAttributes', array('href'));
//new definition
$config->set('HTML.DefinitionID', 'blank_nofollow');
$config->set('HTML.DefinitionRev', 1);
//remove this when you go live and set 'Cache.SerializerPath'
$config->set('Cache.DefinitionImpl', null);
//$config->set('Cache.SerializerPath', 'some/path/for/caching');
$def =& $config->getHTMLDefinition(true);
$a =& $def->addBlankElement('a');
$a->attr_transform_post[] = new HTMLPurifier_AttrTransform_AValidator();
$purifier = new HTMLPurifier($config);
// untrusted input HTML
$html = '<a rel="test" target="test2" href="mylink.php">Simple and short';
$pure_html = $purifier->purify($html);
echo $pure_html;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment