Process Your PHP Form POSTs Faster.

The Scenario:

You setup a contact form for people to send you email.  When the form is submitted, you want to assign each of the POST, GET or REQUEST values to a variable with the same name as the key. (You could do this for a number of reasons, but that’s a different topic.)

The Problem:

Ugh! Doing this can be really time consuming, especially if you have a really long form.  Presonally, I would just use the array element vs. setting creating a new variable, but if you must, I suggest using a foreach() loop to create the variables for you.

The Solution:
Sample form:

1
2
3
4
<form>Email:
<input name="email" type="text" />
<input type="submit" />
</form>

When the form is submitted, use a loop and a variable variable to do the job for you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
if(is_array($_POST))
{
    foreach($_POST as $key => $value)
    {
        $$key = $value; // create variable name from key  
 
        /*
        Assuming `email` was the key, the above would
        create a new variable called $email
        */
    } // end foreach
} // end if
# Process your code here calling each new var
echo $email;
?>

5 Responses to “Process Your PHP Form POSTs Faster.”

Andy Sowards Says:

Your new design is AMAZING :)

marion Says:

Thanks. I think it’s a lot easier to read.

Andy Sowards Says:

It is, should probably work on my blogs Readability :) since SOME people can’t deal with the dark background ;)

Brian Says:

Doing this causes the same security risks as having register_globals on. If you do this make sure you initialize EVERY variable you use. IE:

$success=false; //make sure you do this!!! or it could be overwritten with true
if ($password=”password”)
{
$success=true;
}

Also, you can do the same thing as your code using the PHP extract function with $_POST argument. Same risks.

Marion Dorsett Says:

Brian,

Thanks for the comment regarding security. The context of this post was to address easier ways to manipulate the data by using a loop to deal with the array vs. dealing w/ each variable independently. I actually have a series of functions in my code repository, that I run the arrays through rewriting and creating a whole new array that’s clean and tidy before I begin to process the data, but that’s a topic for another post.

Thanks.

Leave a Reply

Spam Protection by WP-SpamFree