Snippets

Automatically creates variables with the same name as the key in the POST array

This snippet is very helpful for every POST processing. All you need is an array with expected keys in the POST array. This snippet automatically creates variables with the same name as the key in the POST array. If the key is not found in the POST array the variable is set to NULL. Basically you dont need to write:

$username=$_POST["username"];
$age=$_POST["age"];
etc.

This snippet will do this boring part of every PHP code with POST handling so you can fully focus on a validation of the input, because that is much more important.

<?php
$expected=array('username','age','city','street');
foreach($expected as $key){
    if(!empty($_POST[$key])){
        ${key}=$_POST[$key];
    }
    else{
        ${key}=NULL;
    }
}
?>

Source: Pro PHP Security by Chris Snyder and Michael Southwell...

Share this snippet

 

Comments (4) - Leave yours

  1. Patrik Mayer said:

    Hi,

    just have a look at this: http://php.net/manual/de/function.extract.php

    But I think it’s an unclean technique, it mimics the behaviour of register_globals either way… just as the php-manual states.

    Cheers,
    Patrik

  2. Patrik Mayer said:

    Bare with me guys, sorry. Too late and read on the phone… This snippet is absolutely ok!

    Your first define the key’s you want to use from $_POST and dont get everything from the super-global-array to the local scope…

  3. Pako! said:

    I also know another way (3 ways to be exactly):

    extract($_POST) / extract($_GET) / extract($_REQUEST)

    meowww… (:

  4. Michael said:

    Hey dude! You need to pass a var name inside the braces. If you do not do it, you’re passing a constant… so where is ${key} use ${$key} or simply $$key. ;)

Leave a Reply

Your email address will not be published. Required fields are marked *

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!