PHP Tip, generic form mailer

Ever wanted to create a generic web form handler, which can email you the results from all of your site’s forms, similar to the infamous FormMail.cgi? If you have multiple forms and find yourself without the time to write a handler for each one, try using the following script:

#generic form mailer
while(list($key, $val) = each($_POST)){
foreach($val as $element)
$body .= “$key: $elementn”;
$body .= “$key: $valn”;
mail(“”, “Subject”, $body, “From:”);
echo “Thank you! Your submission has been received.”;

This script will take all fields submitted and list them, with both the field name and the submitted value, in an email. For example, if your form contained three fields called name, email, and phonenumber, when submitted, you would be emailed the following:

name: John Doe
phonenumber: 555-1212

This generic form mailer is also savvy enough to deal with inbound posted arrays, if you have several form fields with the same name. Suppose your form contained the following HTML:

<input type=”checkbox” name=”hobbies[]” value=”Computers”>Computers
<input type=”checkbox” name=”hobbies[]” value=”Fishing”>Fishing
<input type=”checkbox” name=”hobbies[]” value=”Hiking”>Hiking

If a visitor selected all three checkboxes and submitted the form, you’d receive an email containing:

hobbies: Computers
hobbies: Fishing
hobbies: Hiking

Using a generic form handler can save you a great deal of time, at the expense of “pretty” formatting for the resulting emails. If you’re willing to sacrifice the attractive formatting possible by writing a specific handler for every form on your site, you can literally set all of your forms to post to this script.

Comments are closed.