This script is only slightly different in concept than the script in Listing 9.5, which simply printed form responses to the screen. In this script, in addition to printing the responses to the screen, you send them to an email address as well.
1: <html> 2: <head> 3: <title>Listing 9.12 Sending mail from the form in Listing 9.11</title> 4: </head> 5: <body> 6: <?php 7: print "Thank you, <b>$_POST[name]</b>, for your message!<br><br>\n\n"; 8: print "Your e-mail address is: <b>$_POST[email]</b><br><br>\n\n"; 9: print "Your message was:<br><br>\n\n"; 10: print "$_POST[message] <br><br>"; 11: //start building the mail string 12: $msg = "Name: $_POST[name]\n"; 13: $msg .= "E-Mail: $_POST[email]\n"; 14: $msg .= "Message: $_POST[message]\n"; 15: //set up the mail 16: $recipient = "firstname.lastname@example.org"; 17: $subject = "Form Submission Results"; 18: $mailheaders = "From: My Web Site <email@example.com> \n"; 19: $mailheaders .= "Reply-To: $_POST[email]"; 20: //send the mail 21: mail($recipient, $subject, $msg, $mailheaders); 22: ?> 23: </body> 24: </html>
The variables you use in lines 7-9 are $_POST[name], $_POST[email], and $_POST[message]?the names of the fields in the form, as part of the $_POST superglobal. That's all well and good for printing the information to the screen, but in this script, you also want to create a string that's sent in email. For this task, you essentially build the email by concatenating strings to form one long message string, using the newline (\n) character to add line breaks where appropriate.
Lines 12 through 14 create the $msg string, which contains the values typed by the user in the form fields. This string is the one sent in the email. Note the use of the concatenation operator (.=) when adding to the variable $msg, in lines 13 and 14.
Lines 16 and 17 are hard-coded variables for the email recipient and the subject of the email message. Replace firstname.lastname@example.org with your own email address, obviously. If you want to change the subject, feel free!
Lines 18 and 19 set up some mail headers, namely From: and Reply-to: headers. You could put any value in the From: header; this is the information that displays in the From or Sender column of your email application when you receive this mail.
The mail() function takes four parameters: the recipient, the subject, the message, and any additional mail headers. The order of these parameters is shown in line 21, and your script is complete after you close up your PHP block and your HTML elements in lines 22-24.
Put these lines into a text file called listing9.12.php, and place that file in your Web server document root. Use your Web browser and go back to the form, enter some information, and press the submission button. You should see something like Figure 9.7 in your browser.
If you then check your email, you should have a message waiting for you. It might look something like Figure 9.8.