Using POST Variables Outside the Loop

Posted by Nessa | Posted in , | Posted on February 24, 2011

4

I was working on this mini contact form the other day where a user basically enters in a bunch of info, the form submits to itself via PHP_SELF, and sends out an email. Oddly enough, once I transferred the form to its permanent home and spent a decent chunk of time trying to figure out why it wasn’t working anymore, I discovered that my developement box still had register_globals enabled from a previous project I was working on.  Doh!

This is part of my loop, which basically just grabs all the $_POST variables and their values to compare them with a previous array ($required) that specifies what values should be present in order for the mailer to determine how much of the form was completed:

// Values passed: domain,email
foreach($_POST as $name => $value) {
    if(in_array($name,$required)){
        if(empty($value) && value != 0 ){
            $complete=0;
        }else{
            $complete=1;
        }
    }
}

The problem is, when I went to use the names of the variables or their values later in the script, I got nothing. This of course would work with register_globals enabled, but since I prefer to work in a more secure environment, a small adjustment was needed in to make those variables available outside the loop:

// Values passed: domain,email
 
foreach($_POST as $name => $value) {
    $$name = trim($value);
    if(in_array($name,$required)){
        if(empty($value) && value != 0 ){
            $complete=0;
        }else{
           $complete=1;
        }
    }
}

Pretty simple stuff, eh? All I did here was tell the loop to actually create a variable and value for each $_POST value that was part of the foreach loop. From there, all I had to do was use these values are normal ($domain,$email,etc)

Be Sociable, Share!

Comments (4)

Have you ever tried this WP Plugin: http://www.viper007bond.com/wordpress-plugins/syntaxhighlighter/

It’s awesome.

Install this plugin to fix your code layout in WordPress http://wordpress.org/extend/plugins/syntaxhighlighter/

Was a good post! :)

Nice share! :D You do know there is a WP plugin for displaying code as is, right?

OT, darn… a Linux chick! I love you already. Ok please don’t get mad at me. I hardly find a chick using Linux, let alone blogging about Linux stuff.

Woot! :)

Post a comment