Unlimited WordPress themes, graphics, videos & courses! Unlimited asset downloads! From $16.50/m
Advertisement
  1. Code
  2. PHP
Code

Create a PHP Email Script and Form

by
Difficulty:IntermediateLength:MediumLanguages:

Forms on websites can be used for a lot of purposes besides being a place to contact the website administrators. In previous posts, I covered how to create a fully functional contact form in PHP and how to build your own Captcha and integrate it in your contact forms

In this tutorial, our focus will be on creating forms in PHP that are meant to serve other purposes like gathering information about a job applicant, booking hotel rooms, or getting information about marriage events from clients.

Choosing the Right Fields for Your Forms

In the contact form tutorial, we learned that different organizations and websites will most probably want to get specific information from people contacting them in order to assist them in the best possible way. For instance, a contact form on a school website might ask parents for information about their kids enrolled in that school. Similarly, the contact form on a shopping website might gather information about the last product people bought in order to serve them better.

If contact forms can vary so much between different websites and organizations, it is reasonable to assume that forms which are supposed to serve completely different purposes have very different fields. For instance, you will most probably ask people booking a hotel room if they will be accompanied by any other adults or children. Asking the same thing of a job applicant would make no sense.

This is an important thing to remember when you follow this tutorial. The basic concept of creating a form, gathering all the information and sending it somewhere by email will stay the same, but the code will almost certainly need changes to work for your case. You might want to add different input fields to your forms and assign different names to those fields. This will then affect the PHP code in the back end. If you make changes in the forms, make sure you update the PHP code as well.

You can take a look at this list of 20 Best PHP email forms to get some inspiration about the layout of form elements or different input fields that you might want to add to your forms.

Creating an HTML Form

In this tutorial, we will create a form to book hotel rooms as an example. For simplicity, we will not use any additional JavaScript or PHP libraries.

With this in mind, let's write the markup of our form. We need to ask people making a reservation their name, email address, and phone number. After that, we ask them to provide details about the number of children and adults that will accompany them, the check-in and check-out dates, and the type of room they prefer. In the end, we will ask them if there is anything else that we show know before their arrival.

We have used two basic patterns to check if the provided name and phone numbers are valid. Phone numbers follow different formats depending on the locale. This means that you will have to update the value of the pattern attribute accordingly.

We have also set the minimum value of adults and children to 1 and 0 respectively. This way, we can prevent people from mistakenly adding negative values.

You can add more elements to this form for other services that the hotel provides like pickup, room service, etc.

Right now, visitors can set both the check-in and check-out dates to a past value. We can avoid that by simply setting the value of the min attribute on both the check-in and check-out dates. In our case, we will set the minimum possible check-in date to be the current day. The value of the min attribute of the check-out date will be the check-in date.

The JavaScript code below will handle all the logic for us. The months are zero-based, so we add 1 to the returned value to get the actual month. The returned date value can be any integer from 1 to 31 depending on the current time.

When the date and month values are in single digits, they are padded with an extra 0 so that the final string stays in a valid format.

The following CodePen demo shows us how the form behaves after adding the above markup and JavaScript functionality.

Sending the Form Data by Email With PHP

The final step involves collecting all the data from our form and sending it to the relevant people in an email. This is actually very easy to do. First, we gather all the information using $_POST variables. Once we have the required information, we sanitize it to remove anything malicious. Finally, we create the body of our HTML email and then send it using the mail() function in PHP.

The following code will go into a file called reservation.php. The file name will be different if you changed the value of the action attribute of the form in the previous section.

We begin by sanitizing the name and email address of the visitor. After that, we sanitize the check-in date, check-out date, number of adults and number of children using the FILTER_SANITIZE_NUMBER_INT flag. This flag removes all characters from the input except digits and + or - signs. It works out great for sanitizing our dates because we expect them in the format YYYY-MM-DD—just digits and the minus sign. You should go through the PHP documentation to learn about all the sanitization and validation flags.

Once we have sanitized all the input, we start preparing our headers. By including Content-type: text/html in the email headers, we will be able to use HTML tags inside our email. For this tutorial, we are keeping it simple and showing all the user data inside a table. Any special message left by people booking a hotel room is shown below the table.

Final Thoughts

In this tutorial, we have covered the basics of creating a PHP email script that sends data from forms that people have filled out. When creating forms, it is important to lay the elements out properly and make sure that you only ask for information that is actually required. Creating an unnecessarily long form with improperly laid out elements will discourage users from filling out the form. You should also make sure that every element is named properly. Proper sanitization of user input is important as well.

If you have never created your own forms and are unfamiliar with PHP, it might be better to consider using scripts created by professionals. We have created this list of 20 Best PHP Email forms to help you get started. These forms come with extra features like Captcha, scheduling emails, and file uploads.

If you have any questions related to this tutorial, please let me know in the comments.

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.