Forum Moderators: coopster
I have been using PHP email forms for quite a while and always have the same problem. It takes forever to build because I have to not only create the form fields, but then I have to declare them FOR the message as well.
For example:
if(!empty($_POST['email'])) {
$email = $_POST['email'];
$emailfrom = $_POST['email'];
} else {
$email = "";
$emailfrom = "NO RETURN SPECIFIED";
}//end if email$msg = "Todays Date: \t ".date("M d, Y")."\n";
$msg .= "Name: \t ".$_POST['fname']."\n";
$msg .= "Email: \t ".$email."\n";
$msg .= "Address: \t ".$_POST['address']."\n";
$msg .= "City: \t ".$_POST['city']."\n";
$msg .= "State: \t ".$_POST['state']."\n";
$msg .= "Zip: \t ".$_POST['zip']."\n";
$msg .= "Phone: \t ".$_POST['phone']."\n";
$msg .= "Message: \t\n ".$_POST['message']."\n\n";
$to = "$sendthisto";
$subject = "Contact Form from Website";
$headers = "From: ".$emailfrom."\n\n";
mail($to, $subject, $msg, $headers);
} else { ?>
etc etc
And for long forms, this is the pits! Is there a better way to do this instead of creating a new line for $msg every time? Maybe it will cycle through the entire form, pull out the information and then post it going by input Name or something?
$input = Array (
'fname' => 'Name',
'email' => 'Email',
'address' => 'Address',
'city' => 'City',
'zip' => 'Zip',
'phone' => 'Phone Number',
'message' => 'Your Message'
);
$msg = "Today's Date: \t ".date("M d, Y")."\n";
foreach ($input as $key=>$value) {
$msg .= "$value \t".$_POST[$key]."\n";
}
This way $input goes at the top of your script or in a constant or configuration variable/include, somewhere easy to access and change, and will affect all mail or response page content.
The odd duck there is $email, but you can figure a way around that. You should not be using uncleansed $_POST variables anyway. Generally I cleanse these and store them in a new array and step through that instead of $_POST.
However, I would still have to manually create that $input array. That is what I am trying to avoid. Having to create all those lines.
I was able to find this code and adapted it:
$form_fields = array_keys($HTTP_GET_VARS);for ($i = 0; $i < sizeof($form_fields); $i++) {
$thisField = $form_fields[$i];
$thisValue = $HTTP_GET_VARS[$thisField];
$msg .= $thisField ." = ". $thisValue ."\n";
}
But am having a problem adapting it to my form. Suggestions?
[edited by: dreamcatcher at 6:31 am (utc) on July 3, 2009]
[edit reason] No urls please! [/edit]
Predefined Variables [php.net]
Superglobals [php.net]