Create your first e-mail form with HTML & PHP

05.04.2014 by Ilia Raiskin

Required Knowledge

Basic HTML and PHP knowledge is highly recommended!
Click here to go to the HTML collection.
Click here to go to the PHP collection.

In this tutorial I'll show you how to create an e-mail form with very basic validation.

First of all we need our form page (practice_mailform.html). We start off with standart HTML. We add a form, with inputs for name, e-mail and message. Of course we also need a submit button. As you can see we use different formats for the text-fields and buttons. For e-mail and name we use <input type="text"/>. As we need a bigger text-field for the message, we use the <textarea> tag. In order to create a submit button, just use <input type="submit">.

The next thing we should do is adding name-attributes to the text fields. We need these later to identify the content with PHP. Additionaly we can already add a value attribute to the submit button in order to set it's text. Last but definitely not least, we add action and method attributes to our form. With <form action=""...> we set the location that the form-data is sent to. Method allows us to set (what a surprise) the method that the data is sent with. The two common methods are POST and GET. In our example we use post. Note that when you're using get the form data is displayed in the URL-field of your browser. As method is not the main focus of this tutorial I'll leave out further explanation and add links with more information (PHP.NET GET / PHP.NET POST).

Now that we're done with our HTML form we need to create the sending/validation system. We start off with creating a PHP file (practice_sendmailform.php). Then we need to fetch and filter the date from the e-mail form. We fetch the data (post format) with $_POST['name'] and assign it to variables. Using htmlspecialchars we can transform unwanted HTML and JS into escaped characters.

Next we create an if condition that "asks" whether all text fields are filled out. Let's assume that this is the case. In our if() we remove escape-slashes from the message, because it could contain quotes that have been escaped (basically escaping quotes means that all quotes get an \ added before them). Finally we can build our message. I used variable names that should be self explaining. $return creates a line break. Also visit our date() cheatsheet by clicking this link. Obviously the message is sent with mail(). The last thing we add here is a paragraph that says that the message has been sent.

The last bit we need is the basic validation. We ask three times whether the text fields are empty or not. Each field has it's own error message. We also add our form again, so that people can add information to the text fields if some are empty. Note that the fetched values are added to the form with the value attribute.

That's it! We're done here. Make sure to try this out. It will definitely help you improve your PHP skills.