using a foreach loop to initialize variables

爷,独闯天下 提交于 2019-12-01 12:22:55

You're not accessing $_POST at all, so all you're doing is taking some array members you defined yourself, filtering them for harmful POST characters (why would you attempt to inject your own code?) and then creating a new array from those self-defined key values.

If I'm guessing right at what you want, it should be this:

foreach(array_keys($insArray) as $key) {
    $insArray[$key] = stripslashes(filter_input(INPUT_POST, $_POST[$key]));
}

The use of stripslashes suggests that you're on a braindead version of PHP which has magic_quotes enable. You should upgrade to a modern version of PHP and/or turn them off.

The solution is change

$key = stripslashes(filter_input(INPUT_POST, $key));

to

$$key = stripslashes(filter_input(INPUT_POST, $key));

See http://www.php.net/manual/en/language.variables.variable.php

Also, recheck your code, which are doing some mistakes..

If I understand you correctly, Im going to suggest this approach:

$defaultValues = array('rUsername'=>'', 'rPass'=>'', 'rQuestion'=>'', 'rAnswer'=>'', 'rFName'=>'', 'rLName'=>'', 'rBDateD'=>'', 'rBDateM'=>'', 'rBDateY'=>'', 'rHCheck'=>'', 'rHCeckOption'=>'', 'rEmail'=>'');
$values = array_map('stripslashes', array_merge($defaultValues, array_filter($_POST)));
extract($values, EXTR_SKIP);
echo $rUsername;
echo $rPass;
.........

By using the snippet above, you have to take into account the following

  • Im using the extract function with EXTR_SKIP so you dont overwrite existing variables. Make sure to only use the variables you need in your code and sanitize them appropietly.

  • By using array_filter on the $_POST superglobal im "erasing" all empty or null variables. so if an expected key was not sent via $_POST, it defaults to the value specified by the $defaultValues array.

  • I dont quite understand why you are using filter_input without the third parameter (filter constants).

Sachin G.

Hope this will help, If not may be I have misunderstood the problem.

Instead of

$key = stripslashes(filter_input(INPUT_POST, $key)); 
$insArray[$key] = $key;

Try

$insArray[$key] =stripslashes(filter_input(INPUT_POST, $key));

Then after the foreach loop

extract($insArray);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!