I was hacking around this morning and wanting to use automatically generate safe-to-use variables from $_POST
. Probably not the best use of extract()
and compact()
, but extract()
allowed me to prefix variable names and compact(explode())
seemed like a neat way to stick everything back into an array after being prefixed.
function sanitizeForm($formVars) {
// prefix $_POST vars so attacker can't try and guess existing
extract($_POST, EXTR_PREFIX_ALL, 'form');
// put the form variables back into an array
$inputArray = compact(explode(' ', $formVars));
$cleanInput = array();
foreach($inputArray as $key => $value) {
$cleanInput[$key] = htmlspecialchars($value);
}
return $cleanInput;
}
The test form I used simply posted firstname
, lastname
, and comments
. Here's the PHP:
if(isset($_POST['submit'])) {
$test = sanitizeForm('form_firstname form_lastname form_comments');
echo('<pre>');
print_r($test);
echo('</pre>');
}
Submitting 'test' for both firstname
and lastname
with the script in comments
:
Array
(
[form_firstname] => test
[form_lastname] => test
[form_comments] => <script>alert('xss')</script>
)