PHP Tutorial – Part 3 of 5

Published on Oct 16, 2008   //  Tutorials

PHPIn Part 1 of our PHP Tutorial series we covered how to use PHP and HTML together and use the print command. In Part 2 of our PHP Tutorial series we covered using variables.

In this tutorial we will cover how to send an email using PHP. If you ever need to capture information from a contact form and email it then using PHP mail is one of the more secure and easy methods of doing so.

To start you will need an html form page which captures the details. I have placed the code into a file so you can easily copy it. Once you have the form setup the way you want create your form.php file.

Place the following code into the form.php which you should have in a text editor:

[code='php'] $emailto = "me@myaddress.com";
$emailsubj = "Email Submission";
$emailmess = "Name: ".$_POST["name"]."\r\n";
$emailmess .= "Email: ".$_POST["email"]."\r\n";
$emailmess .= "Comment: ".$_POST["comment"];
$successpage = "http://www.google.com";
mail($emailto, $emailsubj, $emailmess);
header("Location: $successpage"); /* redirect */
exit;
?>[/code]

The above code should be edited to fit your needs. You can change:

$emailto should be set to the actual email you want the content sent to.
$emailsubj can be set to a more meaningful email subject.
$successpage should be set to a relevant thank you page on your site after the person submits the form.

Again be sure to save the file form.php with a .php extension and upload it to your site. In this example you should see a form and emailed the details when you submit it.

Stay tuned as we will continue this tutorial with more details on using PHP.

1 Comment to “PHP Tutorial – Part 3 of 5”

  • You should also add some headers, so that the email sent has the appropriate from and reply-to emails.

    Change line 8 to:

    mail($emailto, $emailsubj, $emailmess, $headers);

    Put this above line 8:

    $headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();