Skip to content

Instantly share code, notes, and snippets.

@voku
Last active October 30, 2022 03:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voku/2246eefcea1ef2671f18 to your computer and use it in GitHub Desktop.
Save voku/2246eefcea1ef2671f18 to your computer and use it in GitHub Desktop.
a php-function that will fixing utf-8 problems from inputs and prevent XSS attacks
<?php
// require
//
// "Portable UTF-8" -> https://packagist.org/packages/voku/portable-utf8
// "HTMLPurifier" -> https://packagist.org/packages/ezyang/htmlpurifier
use voku\helper\UTF8;
// init HTMLPurifier (TODO: move this e.g. to a WrapperClass)
$allowedElements = false;
$htmlPurifierConfig = HTMLPurifier_Config::createDefault();
if ($allowedElements !== false && is_array($allowedElements)) {
$htmlPurifierConfig->set('HTML.AllowedElements', $allowedElements);
}
$purifier = new HTMLPurifier($htmlPurifierConfig);
/**
* clear the input-array via HTMLPurifier->purify();
*
* @param array $requestVariable WARNING: this is a reference not a variable!!!
* @param $purifier HTMLPurifier
*/
function clearRequest(Array &$requestVariable, HTMLPurifier $purifier)
{
foreach ($requestVariable as &$value) {
if (is_array($value)) {
clearRequest($value, $purifier);
} else {
$value = $purifier->purify(UTF8::urldecode($value));
}
}
}
// clear inputs
clearRequest($_POST, $purifier);
clearRequest($_GET, $purifier);
clearRequest($_REQUEST, $purifier);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment