[Yii] Defending Against CSRF and XSS in Yii [Part 2]

I previously wrote Defending Against CSRF and XSS in Yii [Part 1], but when it came to actual testing, there was a requirement to filter out special characters such as :, :, “, <, >, %, etc.

Yii’s CHtml::purifier actually only filters HTML, and CHtml::encode essentially calls htmlspecialchars:

  • htmlspecialchars only converts <, >, single quotes, double quotes, and &
  • htmlentities converts all HTML entities

As you can see, PHP’s built-in functions cannot filter all special characters. The approach I took was to create a new Filter class within the Yii framework and write a custom specialchar function, allowing you to replace characters as needed. For better performance, it can be defined as public static.

1
2
3
4
5
6
7
class Filter {
    public static function ReplaceSpecialChar($str) {
        $str=str_replace(":",$str); //TODO: replace other chars
        $str = htmlspecialchars($str);
        return $str;
    }
}