I am using extract to get all the values of a form sent by POST and save them in different variables. My doubt is if using extract() with the flag EXTR_SKIP is the 'best way' to prevent security issues, like (maybe?) overwrite values of the form and other security issues that I don't know (My knowledge about web security is quite limited)
I have a lot of inputs and I always like to learn the fastest way, to be more productive (obviously being aware of security
Optimize for being able to read quickly, not being able to write quickly.
But if you really want to go down this route:
<?php
// Important, ONLY allow the indices you really want to support
$whitelist = array_key_whitelist($_POST, [
'foo',
'bar',
'baz',
'moo',
'usr',
'lol'
]);
// Then run extract() as expected
extract($whitelist, EXTR_SKIP);
And the function is, of course:
<?php
/**
* Only allow the whitelisted array keys to exist:
*
* @ref http://stackoverflow.com/a/36193403/2224584
* @param array $input
* @param array $allowedKeys
* @return array
*/
function array_key_whitelist(array $input, array $allowedKeys = []): array
{
$return = [];
foreach ($allowedKeys as $key) {
if (array_key_exists($key, $input)) {
$return[$key] = $input[$key];
}
}
return $return;
}
This is marginally safer than extract()
with EXTR_SKIP
in the context of a loop where, in the future, variables might not get set to their sane values if they were already defined.
But seriously, this is more of a code golf nicety than a practice you should actually follow.