Skip to content

Instantly share code, notes, and snippets.

@adrian-enspired
Last active January 1, 2021 03:13
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adrian-enspired/50591f70d1d88b83383c to your computer and use it in GitHub Desktop.
Save adrian-enspired/50591f70d1d88b83383c to your computer and use it in GitHub Desktop.
I don't actually recommend this approach anymore. you're better off with a more holistic approach to input validation.
<?php
// I first saw this on freenode/##php, from Viper-7.
// first, make an array with ALL of the field names you expect, and default values for each.
// keys are field names; values are field defaults.
$defaults = [
"field1" => "default value",
"field2" => "", // ← default is empty string
"field3" => null // ← no default value
// and so on
];
// next, we're going to match up those defaults with {whatever} the user submitted in POST.
$inputs = array_intersect_key($_POST, $defaults);
// this EXCLUDES any $_POST items that we are not expecting.
// next, we add the defaults (if any) that were missing from $_POST:
$inputs = $inputs + $defaults;
// because $_POST is empty in this example, $inputs is the same as $defaults:
echo "Defaults\n";
var_dump($inputs);
// but, say we had a real POST submission:
$_POST = [
"field1" => "foo",
"field2" => "bar",
"field3" => "baz"
];
// and do the same thing as above:
$inputs = array_intersect_key($_POST, $defaults) + $defaults;
// we see all the submitted fields.
echo "\n\nAll Is Well\n";
var_dump($inputs);
// now, what if an attacker leaves a field out? or adds their own, evil input?
$_POST = [
// field1 is missing
"field2" => "foo",
"evil" => "hax0r!!"
];
// do the same thing as above:
$inputs = array_intersect_key( $_POST,$defaults ) + $defaults;
// no problem.
echo "\n\nSee No Evil\n";
var_dump($inputs);
<?php
/**
* here's a nice and tidy way to
* (a) make sure you only get inputs you expect, and
* (b) make sure any missing inputs have default values.
*
* @param array $input input (e.g., $_POST)
* @param array $defaults map of input keys => default values
* @return array desired input keys with default values where missing
*/
function defaults(array $input, array $defaults) {
return array_intersect_key($input, $defaults) + $defaults;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment