1. Home
  2. Computing & Technology
  3. PHP / MySQL

A Practical PHP Form to Mail

By Angela Bradley, About.com

4 of 4

The PHP Explained

The first three variables we assign in our program ($to, $from, and $name) are all pulled directly from the form data using the $_REQUEST tag. We then define the from header, and a subject for our email (this can be anything you wish.)

Next we create an array; the data on the left is the form fields and the data on the right is the 'Human Friendly" label for each type of content. For example list is our mailing list field from our form, and Mailing List is its label. If you added other fields, or removed some from our example form, you must edit this array appropriately.

Next we define the message body. We use $body to first say what we are sending in the mail (We have received the following information) and then use a FOREACH loop to retrieve the data and its appropriate label from our array. We utilize sprintf() and its associated tags to make sure our data is in string format.

Next we define $headers2, $subject2 and $autoreply. These are the values we will use in our mail to the customer to let them know their form data has been sent to us. You can adjust these all as you see fit.

Finally we check that our required fields (Name and Email) were not left blank before sending the email to our site staff and to the customer.

If this is successful, the user is directed (via the header location tag) to a thank you page. If you prefer you can simply have it print out a success message, similar to our error messages.

Index: A Practical PHP Form to Mail

  1. The HTML Form
  2. The Form Explained
  3. Processing With PHP
  4. The PHP Explained

4 of 4

Explore PHP / MySQL

More from About.com

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. Step By Steps
  5. PHP Email - PHP Email Form - PHP Email Script

©2008 About.com, a part of The New York Times Company.

All rights reserved.