Here comes the fun part, coding the actual PHP!
You may remember that in the first part of the script we changed the 'action' attribute of the <form> tag to point to a page called 'mailer.php', now we just have to code that page.
<?php
$name = $_POST['name']; $comments = $_POST['comments']; |
Remember how we "named" our form fields in the previous page? Well, here's when those names come into play.Once the user hits submit they values of those fields are passed as "POST variables" and the user is redirected to 'mailer.php'.The data passed through the previous page can now be accessed in the form of: $_POST['nameofvariable'], but to make it easier we will assign those POST variables to regular variables. This is done in the $var = $_POST['var'] part.
| mail("webmaster@yourdomain", "Feedback from your website!", "Hi! Somebody sent you comments through your site!\n\nTheir name: $name\n\nTheir comments:\n$comments"); |
What we've been all waiting for, the mailing part. The e-mail is sent to you via PHP's mail(); function, which works in the following way:
mail("you@youremailaddress.com", "The Subject of the E-mail", "The message.") |
You may have noticed that we used '\n\n' in the body of the message, this means "new line" -
whenever \n is typed it will result in a new line in the actual e-mail.
And $name and $comments will of course be the values of the data passed through the form.
Finally, we will tell the user that the message has been sent:
| echo "<p>E-mail sent, thank you.</p>"; |
Let's wrap it all up into one file:
mailer.php
<html> <head> <title>My PHP Mailer</title> </head> <body> <?php $name = $_POST['name']; $comments = $_POST['comments']; mail("webmaster@yourdomain.com", "Feedback from your website!", "Hi! Somebody sent you comments through your site!\n\nTheir name: $name\n\nTheir comments:\n$comments"); echo "<p>E-mail sent, thank you.</p>"; ?> </body> </html> |
You should now know the basics of working with forms, passing data through pages and mailing
using PHP's built-in mail(); function!