Forum Moderators: coopster
The second loop isn't much better, it basically creates a copy of $_POST while emulating magic_quotes, sort of, because it breaks if some elements in $_POST are arrays. It's generally not a good idea to encode your values for a specific format (in this case SQL) so early in your script. If you need to use the values in some other formats, e.g. an email message or echo back to the browser, you need to undo the encoding, an extra step that complicates your program unnecessarily.
There's a reason magic_quotes and register_globals are being deprecated. Shortcuts just leave your program open to bugs and security holes. :)
function getPostVars($vars) {
$values = array();
foreach($vars as $key) {
$values[$key] = $_POST[$key];
}
return $values;
}
extract(getPostVars(array('field1', 'field2', 'etc')));
For security, the important thing is that you only reference selected entries in $_POST so hackers can't inject their own values into other variables.
You could even expand that function to trim values and/or stripslashes if magic_quotes is on, e.g.:
function getPostVars($vars) {
$values = array();
foreach($vars as $key) {
if(isset($_POST[$key]) && !is_array($_POST[$key]))
$values[$key] = trim($_POST[$key]);
else
$values[$key] = $_POST[$key];
}
return $values;
}