PHP Form Mail Script

I’ve had some requests to show you the php script I used to process and send the email from the HTML W3C Tutorial. So here you are. I’ll go through everything, like before, by including the code in black and white and my descriptions of the code in a blue box.

Code is here in a zipped archive.

<html>

You begin a PHP script with the HTML tag, just like normal HTML. You would save the file with the extention .PHP instead of .html though.

<head><title>PHP Mail Sender</title></head>

Here is the definition of the header section using HTML tags. I trust you know what these means. If not view the HTML W3C tutorial here.

<body>

Here is the body tag that tells the browser to display the content that follows.

<?php

This tag tells the browser, that it is going to be reading PHP code, instead of normal HTML.

/* This program will be sent the data from the HTML file formtest2.htm.
It will make sure the required variables have a value set.
If not it will return an error message.
It will create variables and assign the data sent to the correct variables.
It will print on the visitors screen those values sent.
It will assign all of the data sent to a variable named message.
Then email the message to the chosen email address.
If any errors occured, it will make the visitor aware of how to correct the errors. */

This is a PHP comment section, that will list everything this program will try to accomplish. You begin a comment with the code /* and end it with the code */

/* Check if the form was submitted */
if (isset($_POST[‘submitted’])) {
$errors = array(); // Create an Error Array

Here is another comment. Now I’ll describe the second line. In the html file that sent data to this program, there was a line of html that looked like this:
<input type=”hidden” name=”submitted” value=”TRUE” />
This line of HTML code, creates a variable named submitted and assigns the value of TRUE to that variable. Then that variable and value are sent to this application for processing. The line above is asking, “if the variable submitted is set?” You are able to access the variable submitted’s value by surrounding its name with $_POST[‘ and ‘]. If the value is equal to TRUE, which you can see that it is in the html code above, the program should process every statement that lies between the opening bracket { and }.

Then the code: $errors = array(); creates an array that it will store any errors, that occur in. An array is like a box that you can put information in. This line of code says that, “a box should be created and it should be assigned the variable name errors. The code: // Create an Error Array, is another way to comment in PHP. If you type // in PHP code, all information till the end of the line will be ignored. And finally, you end all code statements with a semicolon ( ; ).

/* Check to see if email, subject and message variables have a value */
if (empty($_POST[’email’])) {
$errors[] = ‘Please Enter an Email.’;

}

if (empty($_POST[‘subject’])) {
$errors[] = ‘Please Enter a Subject.’;
}

if (empty($_POST[‘message’])) {
$errors[] = ‘Please Enter a Message.’;
}

These 3 blocks of code perform the same action on 3 different variables, that were sent by the HTML file. The code asks, “Is the variable, that was sent, have a value assigned to it? If it doesn’t put an error message in the error array, or error box. If their is a value assigned to the variable, do nothing.” The code performs this check on the variables email, subject and message.

/* Check to see if any required data was not entered. If an error occured, report that to the visitor */
if (empty($errors)) {

Here we have another comment. Then the code asks, “Does the error array have any errors in it? If not proceed reading the code that lies between the { and } symbols. If their are errors in the error array, skip following the code between the { and } symbols. Then continue reading the code immediately after the symbol }.

/* All form fields are automatically passed to the PHP script through the array $_POST. Then they are assigned to new PHP variables.*/
$email = $_POST[’email’];
$subject = $_POST[‘subject’];
$message = $_POST[‘message’];
$textinput = $_POST[‘textinput’];
$password = $_POST[‘password’];
$radioinput = $_POST[‘radioinput’];
$checkboxinput = $_POST[‘checkboxinput’];
$selectinput = $_POST[‘selectinput’];
$optioninput = $_POST[‘optioninput’];

Here we are taking all of the information that was past from the HTML W3C file and assigning them to a new variable.

/* Print out the information that the user inputted */
echo ” Email: $email <br />”;
echo ” Subject: $subject <br />”;
echo ” Message: $message <br />”;
echo ” Text Input: $textinput <br />”;
echo ” Password Input: $password <br />”;
echo ” Radio Input: $radioinput <br />”;
echo ” Checkbox Input: $checkboxinput <br />”;
echo ” Select Input: $selectinput <br />”;
echo ” Option Input: $optioninput <br />”;

Here we are printing out all of the variables and the variable values. The word echo will send whatever is between the quotes, to the visitor’s browser screen.

/* Assign all of the visitor inputted data to the variable named message */
$message = ‘Text Area: ‘ . $message . ‘ Text Input: ‘ . $textinput . ‘ Password Input: ‘ . $password . ‘ Radio Input: ‘ . $radioinput . ‘ Checkbox Input: ‘ . $checkboxinput . ‘ Select Input: ‘ . $selectinput . ‘ Option Input: ‘ . $optioninput;

Here we are combining strings of text, enclosed with a quote, to variable values. They are combined by typing a period between those strings and variables we want combined. After they are combined into one string, we assign that value to the variable message.

/* Sends the mail and outputs the “Thank you” string if the mail is successfully sent, or the error string otherwise. */
mail($email,$subject,$message);

echo “Message Sent, Thank you <br />”;

First we have a comment. Then we use the mail function to send an email to the email assigned to the variable $email. The subject of the email will be what ever the value of subject was and the message in the email, will be the value assigned to the variable message.

Then we use the echo function to display the words, “Message Sent, Thank you <br />”, on the visitors browser screen.

/* Creates a link the visitor can click to go back to the original page */
echo “<a href=’javascript:history.back(1);’>Click Here to go Back to the Previous Page</a>”;

This line of code uses the echo function to print the link in the browser screen. The line of HTML code, href=’javascript:history.back(1);’, will send the user to that screen which they where previously on. I’ll get into this later in the Javascript Tutorial.

/* If there was an error found, the program will jump down here and print out the errors on the users browser window. */
} else { // Report all errors

Remember way back in the code when we had this if statement:

if (isset($_POST[‘submitted’])) {
$errors = array(); // Create an Error Array

Check back for an explanation of this code. We if the variable submitted didn’t contain a value you would have been sent to this else statement. If the answer was true, then you will skip all of the code that follows the word else and is between the symbols { and }.

echo ‘<h2>An Error Occured</h2>
<p>The Following Error Occured: <br />’;

foreach ($errors as $msg) { // Show each Error
echo ” – $msg<br />\n”;
}

Here we are using the echo function again to write on the visitors screen. As you can see, everything between the quotes following the word echo will be printed on the screen, even if there is a newline in the code. The for each function will sort through the error box or array and if an error is found it will assign that error message to the variable msg and output that error message on the visitors screen.

/* Creates a link the visitor can click to go back to the original page */
echo “<a href=’javascript:history.back(1);’>Click Here to go Back to the Previous Page</a>”;
}
} // Close the Post Submitted Check

?>

A comment is used. Then we use the echo function to create the same link on the visitor’s screen. We use the symbol } twice to close all of the blocks of code. Then to tell the browser that it will not be receiving PHP code that it will have to analyze we close the PHP tag.

</body>
</html>

Here we close the whole PHP / HTML page like before. I hope this tutorial was understandable. If you have any questions leave them in the comment section below.

Here is the code, without my comments. Till next time…

<html>
<head><title>PHP Mail Sender</title></head>
<body>
<?php
/* This program will be sent the data from the HTML file formtest2.htm.
It will make sure the required variables have a value set.
If not it will return an error message.
It will create variables and assign the data sent to the correct variables.
It will print on the visitors screen those values sent.
It will assign all of the data sent to a variable named message.
Then email the message to the chosen email address.
If any errors occured, it will make the visitor aware of how to correct the errors. */

/* Check if the form was submitted */
if (isset($_POST[‘submitted’])) {
$errors = array(); // Create an Error Array

/* Check to see if email, subject and message variables have a value */
if (empty($_POST[’email’])) {
$errors[] = ‘Please Enter an Email.’;
}

if (empty($_POST[‘subject’])) {
$errors[] = ‘Please Enter a Subject.’;
}

if (empty($_POST[‘message’])) {
$errors[] = ‘Please Enter a Message.’;
}

/* Check to see if any required data was not entered. If an error occured, report that to the visitor */
if (empty($errors)) {

/* All form fields are automatically passed to the PHP script through the array $_POST. Then they are assigned to new PHP variables.*/
$email = $_POST[’email’];
$subject = $_POST[‘subject’];
$message = $_POST[‘message’];
$textinput = $_POST[‘textinput’];
$password = $_POST[‘password’];
$radioinput = $_POST[‘radioinput’];
$checkboxinput = $_POST[‘checkboxinput’];
$selectinput = $_POST[‘selectinput’];
$optioninput = $_POST[‘optioninput’];

/* Print out the information that the user inputted */
echo ” Email: $email <br />”;
echo ” Subject: $subject <br />”;
echo ” Message: $message <br />”;
echo ” Text Input: $textinput <br />”;
echo ” Password Input: $password <br />”;
echo ” Radio Input: $radioinput <br />”;
echo ” Checkbox Input: $checkboxinput <br />”;
echo ” Select Input: $selectinput <br />”;
echo ” Option Input: $optioninput <br />”;

/* Assign all of the visitor inputted data to the variable named message */
$message = ‘Text Area: ‘ . $message . ‘ Text Input: ‘ . $textinput . ‘ Password Input: ‘ . $password . ‘ Radio Input: ‘ . $radioinput . ‘ Checkbox Input: ‘ . $checkboxinput . ‘ Select Input: ‘ . $selectinput . ‘ Option Input: ‘ . $optioninput;

/* Sends the mail and outputs the “Thank you” string if the mail is successfully sent, or the error string otherwise. */
mail($email,$subject,$message);

echo “Message Sent, Thank you <br />”;

/* Creates a link the visitor can click to go back to the original page */
echo “<a href=’javascript:history.back(1);’>Click Here to go Back to the Previous Page</a>”;

/* If there was an error found, the program will jump down here and print out the errors on the users browser window. */
} else { // Report all errors

echo ‘<h2>An Error Occured</h2>
<p>The Following Error Occured: <br />’;

foreach ($errors as $msg) { // Show each Error
echo ” – $msg<br />\n”;
}
/* Creates a link the visitor can click to go back to the original page */
echo “<a href=’javascript:history.back(1);’>Click Here to go Back to the Previous Page</a>”;
}
} // Close the Post Submitted Check

?>
</body>
</html>

24 Responses to “PHP Form Mail Script”

  1. awesome stuff, cheers man

  2. Excellent. Thanks so much for the post. -Kate

  3. hospedagem says:

    this post will help me a lot for my work in college.

  4. Hi Sir,
    I have one question here. If we have lots of rules and regulations with xhtml and html 5, and not all the browsers support html 5, then
    why and when do we use xhtml and html 5

    Why not only use html instead of those two, with combinations of css to make easier for all browser to be supported.

    • admin says:

      xHTML if you follow the Strict guidelines is supposed to work perfectly in any browser. Of course you’ll have to use good CSS code as well to get everything to show up correctly in every browser. At times you have to create multiple style sheets for each brand of browser, but this isn’t always the case.

      I agree with you in regards to HTML5. Each major browser is using different versions of the HTML5 markup. In my opinion it is better to wait for a stable format that they all can agree on

  5. Hi, First of thank you so much for your quick response. I have been watching your tutorials closely and making notes of what is taught here. I wish to be good web designer like you, and consider you as my teacher. I have couple of questions here:

    I have go through many SEO article and website content writing
    SEO is little bit trick and needs proper attention to design a website seo friendly
    But now my question is how to write good content for the website to make it noticeable in the search engines. Where do I go to find content for any website..What all researches do I need to do and put keywords in the article.
    Please advise how to write article for any website and the important points, I need to remember while writing for any website.

  6. Hi Derek,
    While watching XML tutorials after finishing HTML, XHTML, HTML 5,
    I find XML tutorials very complicated and I feel there is so much to learn with definitions with less number of examples.
    If you could add more examples for XML with definitions like you did before for others, It will be easier for us to learn XML very well

  7. Hi Derek,
    I want to ask one more thing, it is not regarding tutorials but about my personal life. I find your advices very useful like you did before.
    I hope this time also I will get the answer from you and suggestions are very important for me.
    I am from India and speak regional languages very well like Hindi and other mother tongue languages. But when we join school, English becomes our secondary languages after Hindi. English is a universal language here. If person know English, he gets the job, otherwise not.
    I feel very uncomfortable while speaking secondary language English. I don’t know why I am always scared of people around me when it comes to give presentation or speak formally in English. I write well, but Why I am always scared of speaking in front of people. There are couple of reasons which I feel like
    I feel people will laugh at me when I speak English
    I speak very low with less pitch
    I stammer a lot when I speak in English
    when I start speaking I don’t find appropriate words to express myself
    although I know more 3000 English words, but those word don’t come to my mind when I speak English
    Please suggest what needs to be done. What all i have to do to build my confidence level high. When I hear you saying in tutorials I feel you are the best person with whom I can discuss my problems

    Thanks
    jagan

    • admin says:

      I used to be very self conscious as well. I think it has to deal with how you are raised? My personality forced me to care way to much about how others saw me. I am driven to accomplish every task no matter how impossible it may be. That weakness allowed people to manipulate me into working for them for free. You should probably personality test yourself to spot your strengths and weaknesses. Here is my personality test.

      Either way, I was successful, but eventually feel into a rut. I had changed career paths and was out of my element. I tried to learn my way through the situation, but there were to many people limiting my ability to do that (I was a stock broker). So, I did what many people thought was the most degrading thing ever. I became a telemarketer, so I could learn how to talk on the phone and increase my ability to sell, socialize, negotiate, etc.

      With this new knowledge I figured out that most people (Even your Boss) don’t have the answers. I figured out that if I wanted to succeed I needed to figure out My Way of succeeding. I forced myself to ignore the experts. Over time I have pretty much eliminated any need to get the approval of others. Having hundreds of people reject you is a great way to eliminate the need to avoid rejection. (Telemarketing did that for me)

      I went from working in the telemarketing industry to complete destroying every sales record when I went back into the financial services world. I went from not getting sales, to ranking in the top 5% in 1 year! That happened because I refused to quit, take advice, get bullied, etc.

      You have the ability to be better than everyone around you if you are willing to work harder. It will take time. Don’t think that you’ll be a super star over night. Take chances and experience a life worth talking about. Build a database of great stories and you’ll be a person people admire

  8. jagannath ghosh says:

    Hi, Derek,

    I am using WordPress tool to design the website, where I find header , footer, sidebars. and I am using wow slider in the wordpress. But the problem is, I am only able to use wowslider (slide show) in the body of the template not in the header. Can Please advise me how can I use wow slider in the header of the template. and also I want to put logo and menu bar at the top of the template. Please advice what needs to be done.

    • admin says:

      I’ve never used Wowslider, but if you are able to use it in the body, I don’t see why you can’t use it in the header? What errors are you getting?

  9. jagannath ghosh says:

    Hi Derek,

    I am using WordPress tool for designing my website. I find it very complicated when it comes to coding. I have little confusing, here about how to put wowslider in the header. I am able to put that plugin (slide show) in the body of the wordpress template. But I want that plug in the header.
    Please advise what needs to be done.

  10. jagannath ghosh says:

    Hi, Derek
    I am great fan of your tutorials and the way you teach, I love that. and you will be glad to hear that after watching your tutorials, I have started making live websites and also got some projects online. I just started these par-time job at home, I know I will face trouble in making websites.
    I am making a website for a client, but he is not happy with the design that I made, I changed the themes four times but he is not happy and I am afraid that he might ask for the refund. I am trying my best to present each time a good look in the website. But he is not at all happy with the layout.
    Please help me or else he will ask for refund and my entire hard work will be in vain.
    Let me explain you little bit about my client
    my client name is Maxpro Business solution
    It deals with ISO standards like ISO 9001, ISO 14001,18001,22000 etc.
    This is website url which I created http://maxproindia.in/…I only created the layout not decorated the website, which I will do later.
    My client is saying to make something like http://www.saiqb.in/services.html

    I have tried a lot to give a satisfying look , but my client is not happy….Please advise what needs to be done.

    • jagannath ghosh says:

      Hi Derek,
      The above URL is http://maxproindia.in/ which I created using wordpress and http://www.saiqb.in/services.html which my client needs to be alike

      • admin says:

        The 2 sites look very similar. The only difference is that you have a liquid layout while theirs is a specific size. If the client likes that better just define a maximum width for the site of 1000 px. Sometimes clients are just stubborn. I turn down over 75% of the business I get.

        Did they sign off on the design you presented to them? If they did and you copied that design they can’t demand a refund. If not then get them to list the exact changes they want. Make them list them to the tiniest detail. Get them to sign off on a mockup and then fix that.

        I hope that helps

  11. Jagannath says:

    Hi Derek,
    I hope that works.
    Sometimes I get tough projects and I deny it, as I am not able to do it and dont have depth knowledge of webdesigning.
    Will you work with me so we can have egual benefits, If yes, send me an email and if not, ignore this. I wont mind at all.
    Thanks
    Jagan

  12. amal says:

    very useful and very nice article thank you

  13. Anil says:

    Man … you are dude
    God bless you… i have been following your tutorials from past 1 year . You are better than the sum of all teachers of my college 🙂

Leave a Reply

Your email address will not be published.

Google+