Creating a Form Mail Script


The desired result from the comments form you've been working with in this lesson is to provide a way of sending user-submitted comments by email to the owner of a website. Now you'll learn how to put together a form handler script to create this component for a website.

The mail Function

PHP's mail function sends an email message, using your system's mailer program. On Linux/Unix systems, the sendmail utility is used to put a message into the outbound queue. On Windows machines, it usually sends via SMTP, and the name of the relay server must be defined in php.ini for this to work properly. Lesson 23, "PHP Configuration," looks at configuration issues in more detail.

The three required arguments to mail are the recipient's email address, the message subject, and the message body. An optional fourth argument can contain additional mail headers to be sent; this is useful for setting the From: address or adding a Cc: recipient.

The script send_comments.php in Listing 11.2 takes the data sent from the comments form and sends it on to the owner of the website by email.

This script performs a loop through all the elements in $_POST and builds up the string $body, which becomes the body text of the email message. Note that \n characters are used to separate lines in the output because a plain-text email is created, which means no HTML formatting is required.

Listing 11.2. send_comments.php
 <?php $body = "These comments were sent via the website\n\n"; foreach($_POST as $field => $value) {   $body .= sprintf("%s = %s\n", $field, $value); } mail("owner@website.com", "Comments sent via website", $body,            'From: "WebComments" <comments@website.com>'); ?> <H1>Thank You</H1> Your comments have been sent! 

The email sent to the site owner should look something like the following:

 The following comments were submitted via the website name = Chris Newman email = chris@lightwood.net gender = m referrer = search may_contact = Y comments = This is my favorite website ever 

The format of this email is very rough because each line is generated automatically. Of course, if you prefer, you could spend much longer creating a nicely formatted email; for instance, you could replace the coded values of gender and referrer with their full descriptions.



    Sams Teach Yourself PHP in 10 Minutes
    Sams Teach Yourself PHP in 10 Minutes
    ISBN: 0672327627
    EAN: 2147483647
    Year: 2005
    Pages: 151
    Authors: Chris Newman

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net