skip to Main Content

I’d like to pull all the names of fields from a submitted form, and create variables from them automatically. Not much of a problem as my code1 below shows. BUT I’d now like to put the code in a function that I can call from many PHP form processors, and have the newly created variables be accessible in the CALLING context. My code2 below is the best I can do; is there a safer, better way???

CODE1:

foreach($_POST as $key => $value){
   $$key = filter_var($value, FILTER_SANITIZE_STRING);
}
unset($key,$value);

CODE2: (resides in included file)

function test(){
        foreach($_POST as $key => $value){
            global $$key; <<<------ my best attempt
            $$key = filter_var($value, FILTER_SANITIZE_STRING);
        }
        unset($key,$value);
}

2

Answers


  1. I’d like to pull all the names of fields from a submitted form, and create variables from them automatically.

    That was actually a PHP bultin feature from the beginning, that was eventually removed from the language given how troublesome it was.

    If you’re happy with variables popping up from nowhere and the excitement of being able to be hacked, you need to add your variables to the $GLOBALS superglobal array. That will make them available in global scope.

    function test() {
        foreach ($_POST as $key => $value){
            $GLOBALS[$key] = filter_var($value, FILTER_SANITIZE_STRING);
        }
    }
    

    is there a safer, better way???

    The simplest way to handle variable lists of variables is to use an array. It’s also safer because site visitors cannot overwrite random variables:

    function test(): array {
        $sanitized = [];
        foreach ($_POST as $key => $value) {
            $sanitized[$key] = filter_var($value, FILTER_SANITIZE_STRING);
        }
        return $sanitized;
    }
    

    But I think you should reconsider what you’re even trying to accomplish here. FILTER_SANITIZE_STRING doesn’t do anything useful, and it’s unclear why you can’t know in advance what variables to expect from your form. If you look for simplicity and security, I’d vote for this:

    $foo = $_POST['foo'] ?? null;
    $bar = $_POST['bar'] ?? null;
    

    … for every variable. Replace null with any other default value you prefer.

    Login or Signup to reply.
  2. have the newly created variables be accessible in the CALLING context.

    This is easy. And a very common feature: the return value of that function.

    So within the function build the variable table in form of a PHP array, then return the array.

    In the calling context receive it then and have all form variables accessible by their name as array keys.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search