Snippet Name: XSS Sanitizer Function
Description: Data sanitizing function for cleaning out malicious code or characters from input data. Helps guard against Cross Site Scripting attacks (XSS)
Also see: » Censor Message Text
» Vulnerability Tester
» Block IP Addresses
» Ban Proxy Servers
» Bad Word Filter
» Anti-Flood Protection
» Anti-SQL Injection Function
» Filter non-alphanumeric characters
Comment: (none)
Language:
Highlight Mode: PHP
Last Modified: March 16th, 2009
|
<?PHP
/* CLEANS AGAINST XSS
*
* NOTE all credits goes to codeigniter.com
* @param string $str - string to check
* @param string $charset - character set (default ISO-8859-1)
* @return string|bool $value sanitized string
*/
FUNCTION ft_xss($str, $charset = 'ISO-8859-1') {
/*
* Remove Null Characters
*
* This prevents sandwiching null characters
* between ASCII characters, like Java\0script.
*
*/
$str = PREG_REPLACE('/\0+/', '', $str);
$str = PREG_REPLACE('/(\\\\0)+/', '', $str);
/*
* Validate standard character entities
*
* Add a semicolon if missing. We do this to enable
* the conversion of entities to ASCII later.
*
*/
$str = PREG_REPLACE('#(&\#*\w+)[\x00-\x20]+;#u',"\\1;",$str);
/*
* Validate UTF16 two byte encoding (x00)
*
* Just as above, adds a semicolon if missing.
*
*/
$str = PREG_REPLACE('#(&\#x*)([0-9A-F]+);*#iu',"\\1\\2;",$str);
/*
* URL Decode
*
* Just in case stuff like this is submitted:
*
* <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
*
* Note: Normally urldecode() would be easier but it removes plus signs
*
*/
$str = PREG_REPLACE("/%u0([a-z0-9]{3})/i", " |