Htmlpurifier and the CodeIgniter framework

Intro

HtmlPurifier is a standards-compliant HTML filter library written in PHP. HTML Purifier will not only remove all malicious code (better known as XSS) with a thoroughly audited, secure yet permissive whitelist, it will also make sure your documents are standards compliant.

Although Codeigniter comes with it’s own XSS filtering method $this->input->xss_clean() I prefer the use of the HtmlPurifier because of 2 reasons :
1) HTMLpurifier will make sure that user input is converted to valid xhtml
2) HTMLpurifier is tested against every element on the notorious XSS cheat sheet

Installing htmlPurifier in codeigniter

Since codeigniter is PHP4 and PHP5 compatible we’ll start out by downloading the php4 compatible version of htmlPurifier (http://htmlpurifier.org/download.html)

Once you’ve downloaded and extracted the archive you’ll just have to copy the contents of the /htmlpurifier-2.0.1/library folder into your codeigniter /system/application/libraries folder.

HtmlPurifier comes with an HTMLPurifier.auto.php file that automagically changes your include path to include the neccessary folder. We’ll delete this file and make one small change to HTMLPurifier.php.

Just add

set_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path() );

just below the

<?php

line in HTMLPurifier.php and we’re ready to go.

Small demo

Add this testcontroller and check out the results :

<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Test extends Controller {
    function Test()
    {
        parent::Controller();
    }
 
    function index()
    {
        $this->load->library('HTMLPurifier');
        $dirty_html = '<a href="javascript:alert(\'test\')">ds</a><p>test<br /><img src="noalt.jpg">';
        $config = HTMLPurifier_Config::createDefault();
        $clean_html = $this->htmlpurifier->purify( $dirty_html , $config );
        echo $clean_html;
    }
}
?>