BN83
BN83

Reputation: 902

Process form fields with foreach loop on posting form?

I'm posting 20 results from a form, to be used on the next page, is there a quick foreach way of posting:

$UserID1 = $_POST['UserID1'];

Where the ID changes each time rather than listing it 20 odd times? I thought a foreach statement, but i'm not too sure where to begin with it?

Upvotes: 0

Views: 131

Answers (3)

AJReading
AJReading

Reputation: 1223

The other answers will do the job just fine, however they introduce security issues.

Code such as:

foreach($_POST as $key => $value){
     $$key = $value; //Assign the value to a variable named after $key
}

Allows me to post any form field I wish to your page and alter any variables value, for example, say you have code something like this elsewhere:

if ($validation) { // Do something }

Then I am able to post a form field named validation with a value of 1 and manipulate your code as that would assign a variable called $validation to a value of my choosing.

Using that code to assign variables from all your $_POST values automatically, is the same as using register_globals which was deprecated due to it's blatent security issues. See: http://www.php.net/manual/en/security.globals.php

If you must do this, you must check that the posted values are something that you expect. For example, check for the existance of UserID. This will only allow the creation of variables if they begin with UserID:

foreach($_POST as $key => $value) {
    if (substr($key, 0, 6) == 'UserID') {
        $$key = $value; //Assign the value to a variable named after $key
    }
}

This will check for $_POST['UserID1'] and create $UserID1 and $_POST['UserID2'] and create $UserID2...

Upvotes: 1

John Conde
John Conde

Reputation: 219804

You can use extract():

extract($_POST);

echo $UserID1; // This now works

This is not considered a good programming practice but will do what you want.

Upvotes: 2

tchow002
tchow002

Reputation: 91

foreach($_POST as $key => $value){
  $$key = $value; //Assign the value to a variable named after $key
}

Upvotes: 1

Related Questions