Search code examples
phpmysqlpdohttp-postsql-injection

PHP Post vars to var names ok with PDO?


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;
}

Solution

  • 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: