Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active January 18, 2023 22:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stemar/6dfd81e08243e704ca0ceb3b537fcf58 to your computer and use it in GitHub Desktop.
Save stemar/6dfd81e08243e704ca0ceb3b537fcf58 to your computer and use it in GitHub Desktop.
Filter out non-allowed parameters in the request input and protect parameter values against XSS.
<?php
/**
* Filter out non-allowed parameters in the request input and protect parameter values against XSS
*
* @param int $type INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV
* @param array $allowed_params
* @link https://www.php.net/manual/en/function.filter-input-array.php
* @return array
*/
function sanitize_input_array($type, array $allowed_params) {
return filter_input_array($type, array_fill_keys($allowed_params, array(
'filter' => FILTER_CALLBACK,
'options' => function ($value) {
return trim(strip_tags($value));
}
)));
}
/*
Usage:
http://example.com/index.php?full_name=`Shorty`%20O'Reilly&email=%20<script>alert('xss');</script>%20&array[][]=<b>10</b>&submit=Send
$allowed_params = array('submit', 'full_name', 'email', 'array', 'other');
$get = sanitize_input_array(INPUT_GET, $allowed_params);
$post = sanitize_input_array(INPUT_POST, $allowed_params);
Result:
var_dump($get);
array(6) {
'submit' =>
string(4) "Send"
'email' =>
string(13) "alert('xss');"
'array' =>
array(1) {
[0] =>
array(1) {
[0] =>
string(2) "10"
}
}
'full_name' =>
string(17) "`Shorty` O'Reilly"
'other' =>
NULL
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment