1

Is there anything wrong with doing this? Ive looked everywhere and it doesnt seem like this is a common thing? is there a built in function im not aware of that does this? Im using PDO for inputs so I am assuming this is fine.

thanks for ANY help!!

foreach($_POST as $post => $var){
    ${$post} =  $var;
}
Ryan Knol
  • 304
  • 2
  • 7
  • 2
    That's basically `extract()`. Why did you assume it is relevant to PDO? – mario Nov 11 '15 at 01:33
  • No, don’t do this. Users can modify *any* variable with that, including $GLOBALS, $_SESSION, $_SERVER, etc. – Gumbo Nov 11 '15 at 06:10

1 Answers1

2

Warning

As @Gumbo stated, this is, in no way, what you want to do. You should avoid doing anything like this with super globals in any sense. You're better off controlling each aspect as best as possible and assigning the variables properly, as best practice permits. i.e.

$a = 'derp';

What you're doing is called Variable Variable and is built into PHP. It essentially allows you to dynamically create variables for use within the current scope.

Take a $_POST array of the following:

Array (
    [a] => 'derp'
)

Now with your current code, you'll be dynamically creating & assigning a variable:

foreach($_POST as $post => $var){
    ${$post} =  $var;
}

Which in turn, allows you to access said variable as the key:

echo $a; // would echo out derp

From personal experience, this isn't always necessary and an issue you could potentially run into is overwriting a variable that has already been set, in turn, producing unwanted/unexplained output.


You'd be best to have a read of these answers to gain a wider understanding of what you're currently doing:

Community
  • 1
  • 1
Darren
  • 13,050
  • 4
  • 41
  • 79
  • Allowing users to populate arbitrary variables is rather how you get hacked: `_SESSION[user]=admin` – Gumbo Nov 11 '15 at 06:13
  • @Gumbo I'll modify answer to note that, was just stating exactly what OP is actually doing via using this. – Darren Nov 11 '15 at 06:18