Scenario: My PHP script requires 10 POST strings to work. The value of all of them needs to be escaped with htmlspecialchars(). So the first lines of the script look like this:
$var1 = htmlspecialchars($_POST['var1']);
$var2 = htmlspecialchars($_POST['var2']);
// And more. You get the point.
This is some code that could simplify it:
foreach($_POST as $key => $value){
$$key = htmlspecialchars($_POST[$value]);
}
I’m unsure about the $$ with user input. I guess somebody could send many POST requests I don’t need and block the server with that. Is this realistic?
The foreach code would be at the very top of my script. So it won’t be able to overwrite any other variables.
Rather than just blindly handling everything in
$_POST(although just passing them throughhtmlspecialchars()is pretty harmless), you can use a whitelist of keys that are acceptable:This evades the possibility of a malicious user submitting hundreds of values to POST and consuming extra system resources.
Update
Commenters are correct. It is better to iterate through the whitelist than
$_POST: