Sending Email


One of my absolute favorite things about PHP is how easy it is to send an email. On a properly configured server, the process is as simple as using the mail() function.

 mail ($to, $subject, $body); 

The $to value should be an email address or a series of addresses, separated by commas. The $subject value will create the email's subject line, and $body is where you put the contents of the email. Use the newline character (\n) within double quotation marks when creating your body to make the text go over multiple lines.

The mail() function takes a fourth, optional parameter for additional headers. This is where you could set the From, Reply-To, Cc, Bcc, and similar settings. For example,

 mail ('phpmysql2@dmcinsights.com',   'Question regarding Script 3.13,   $body, 'From: person@address.com); 

To use multiple headers of different types in your email, separate each with \r\n:

 $headers = "From: John@Doe.com\r\n"; $headers .= "Cc: Jane@Doe.com, Joe@Doe.  com\r\n; mail ('phpmysql2@dmcinsights.com',   'Question regarding Script 3.13,   $body, $headers); 

As the last example in this chapter, a simple registration form will be created that will also send an email upon successful registration. While I'm at it, this example will also demonstrate an easy way to handle and report multiple form-submission errors.

To send email

1.

Begin a new PHP script in your text editor (Script 3.13).

 <?php # Script 3.13 - register.php $page_title = 'Register'; include ('./includes/header.html'); 

Script 3.13. PHP's mail() function is surprisingly easy to use.


2.

Create the conditional for checking if the form has been submitted and then create a variable to track registration errors.

 if (isset($_POST['submitted'])) {   $errors = array(); 

The $errors variable will store all of the accumulated errors from validating the form data. It's initialized here as an array, which is not technically required but is good programming style.

3.

Validate the name and email address.

 if (empty($_POST['name'])) {   $errors[] = 'You forgot to enter    your name.'; } if (empty($_POST['email'])) {   $errors[] = 'You forgot to enter     your email address.'; } 

These two text inputs are validated using the most minimal technique: making sure they aren't empty. If either is empty, a specific message is added as an element to the $errors array.

In Chapter 10, "Web Application Security," you'll see how to use regular expressions to help validate a submitted email address.

4.

Validate the password.

 if (!empty($_POST['password1'])) {   if ($_POST['password1'] != $_POST    ['password2]) {     $errors[] = 'Your password did      not match the confirmed       password.';   } } else {   $errors[] = 'You forgot to enter    your password.'; } 

There are two different validations for the password. First you must check that it's not empty. Second, the password must match the confirmed password. If either condition is false, another error message is added to the array.

5.

Create a conditional that checks if errors occurred.

 if (empty($errors)) { 

If no errors occurred, then the $errors array is still empty, and the email can be sent.

6.

Send the email.

 $body = "Thank you for registering  with our site!\nYour password is  '{$_POST['password1]}'.  \n\nSincerely,\nUs; mail ($_POST['email'], 'Thank you  for registering!', $body, 'From:  admin@site.com); 

To send the email, I first build up my email body and assign that to the $body variable, and then I use the mail() function.

7.

Print a message to the user.

 echo '<h1 >Thank you!  </h1> <p>You are now registered. An email  has been sent to your email address  confirming the information.  </p><p><br /></p>'; 

Obviously the script doesn't yet register the user, but that functionality will be added in due time.

8.

Complete the inner conditional, reporting on the errors.

 } else {   echo '<h1 >Error!</h1>   <p >The following    error(s) occurred:<br />';   foreach ($errors as $msg) {   echo " - $msg<br />\n";   }   echo '</p><p>Please go back and    try again.</p><p><br /></p>'; } 

Since $errors is an array, all of the error messages can easily be printed out using a foreach loop. The result will be a simply formatted list of problems (Figure 3.21).

Figure 3.21. If the form isn't filled out completely, error messages are generated.


9.

Complete the main if and close the PHP tags.

 }else { ?> 

This closes the if block that checks if the form has been submitted. Now the form itself will be created, outside of the PHP tags.

10.

Create the HTML form.

 <h2>Register</h2> <form action="register.php"   method="post>   <p>Name: <input type="text"     name="name size="20"     maxlength="40 /></p>   <p>Email Address: <input     type="text name="email"     size="20 maxlength="40" /> </p>   <p>Password: <input     type="password     name="password1 size="10"     maxlength="20 /></p>   <p>Confirm Password: <input     type="password     name="password2 size="10"     maxlength="20 /></p>   <p><input type="submit"     name="submit value="Register"     /></p>   <input type="hidden"     name="submitted value="TRUE" /> </form> 

There's nothing particularly new here, except that the password is requested twice. This is a smart step to take, since the password is an unreadable input (Figure 3.22). If you only take the password once and the user mistypes their entry, they may not know what their password actually is.

Figure 3.22. The registration form…


11.

Complete the PHP page.

 <?php } include ('./includes/footer.html'); ?> 

The closing curly brace completes the main conditional (that checks if the form has been submitted and displays it otherwise).

12.

Save the file as register.php, upload to your Web server, and test in your Web browser (Figure 3.23).

Figure 3.23. …and its successful completion.


See the sidebar "PHP mail() Dependencies" if you see an odd error message (about From headers missing or no SMTP server) or if you never receive the email.

13.

Check your email to confirm that you received the message (Figure 3.24).

Figure 3.24. The email I received from the registration page.


Tips

  • On someprimarily Unixsystems, the \r\n characters aren't handled properly. If you have problems with them, use just \n instead.

  • The mail() function returns a 1 or a 0 indicating the success of the function call. This is not the same thing as the email successfully being sent or received. You cannot easily test for either using PHP.

  • While it's easy to send a simple message with the mail() function, sending HTML emails or emails with attachments involves more work. In Chapter 11, "Extended Topics," I discuss the PEAR library of code. One of the classes in PEARMime_Mailcan send HTML emails.


PHP mail() Dependencies

PHP's mail() function doesn't actually send the email itself. Instead, it tells the mail server running on the computer to do so. What this means is that your computer must have a working mail server in order for this function to work.

If you have a computer running a Unix variant or if you are running your Web site through a professional host, this should not be a problem. But if you are running PHP on your own computer, you'll probably need to make adjustments.

If you are running Windows and have an Internet service provider (ISP) that provides you with an SMTP server (like smtp.comcast.net), this information can be set in the php.ini file. Unfortunately, this will only work if your ISP does not require authenticationa username and password combinationto use the SMTP server. Otherwise, you'll need to install an SMTP server on your computer. There are plenty available, and they're not that hard to install and use: just search the Internet for free windows smtp server and you'll see some options.

If you are running Mac OS X, you'll need to enable the built-in SMTP server (either sendmail or postfix, depending upon the specific version of Mac OS X you are running). You can find instructions online for doing so (search with enable sendmail "Mac OS X").




    PHP and MySQL for Dynamic Web Sites. Visual QuickPro Guide
    PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (2nd Edition)
    ISBN: 0321336577
    EAN: 2147483647
    Year: 2005
    Pages: 166
    Authors: Larry Ullman

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