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 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 backend. 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 also not use any additional JavaScript or PHP libraries.
With this in mind, lets 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 along with the types of room they prefer. In the end we will ask them if there is anything else that we show know before their arrival.
<form action="reservation.php" method="post"> <div class="elem-group"> <label for="name">Your Name</label> <input type="text" id="name" name="visitor_name" placeholder="John Doe" pattern=[A-Zsa-z]{3,20} required> </div> <div class="elem-group"> <label for="email">Your E-mail</label> <input type="email" id="email" name="visitor_email" placeholder="[email protected]" required> </div> <div class="elem-group"> <label for="phone">Your Phone</label> <input type="tel" id="phone" name="visitor_phone" placeholder="498-348-3872" pattern=(d{3})-?s?(d{3})-?s?(d{4}) required> </div> <hr> <div class="elem-group inlined"> <label for="adult">Adults</label> <input type="number" id="adult" name="total_adults" placeholder="2" min="1" required> </div> <div class="elem-group inlined"> <label for="child">Children</label> <input type="number" id="child" name="total_children" placeholder="2" min="0" required> </div> <div class="elem-group inlined"> <label for="checkin-date">Check-in Date</label> <input type="date" id="checkin-date" name="checkin" required> </div> <div class="elem-group inlined"> <label for="checkout-date">Check-out Date</label> <input type="date" id="checkout-date" name="checkout" required> </div> <div class="elem-group"> <label for="room-selection">Select Room Preference</label> <select id="room-selection" name="room_preference" required> <option value="">Choose a Room from the List</option> <option value="connecting">Connecting</option> <option value="adjoining">Adjoining</option> <option value="adjacent">Adjacent</option> </select> </div> <hr> <div class="elem-group"> <label for="message">Anything Else?</label> <textarea id="message" name="visitor_message" placeholder="Tell us anything else that might be important." required></textarea> </div> <button type="submit">Book The Rooms</button> </form>
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 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 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 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.
var currentDateTime = new Date(); var year = currentDateTime.getFullYear(); var month = (currentDateTime.getMonth() + 1); var date = currentDateTime.getDate(); if(date < 10) { date = '0' + date; } if(month < 10) { month = '0' + month; } var dateTomorrow = year + "-" + month + "-" + date; var checkinElem = document.querySelector("#checkin-date"); var checkoutElem = document.querySelector("#checkout-date"); checkinElem.setAttribute("min", dateTomorrow); checkinElem.onchange = function () { checkoutElem.setAttribute("min", this.value); }
The following CodePen demo shows the 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 concerned 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 action
attribute of the from in previous section.
<?php if($_POST) { $visitor_name = ""; $visitor_email = ""; $visitor_phone = ""; $total_adults = ""; $total_children = ""; $checkin_date = ""; $checkout_date = ""; $room_type = ""; $visitor_message = ""; if(isset($_POST['visitor_name'])) { $visitor_name = filter_var($_POST['visitor_name'], FILTER_SANITIZE_STRING); } if(isset($_POST['visitor_email'])) { $visitor_email = str_replace(array("r", "n", "%0a", "%0d"), '', $_POST['visitor_email']); $visitor_email = filter_var($visitor_email, FILTER_VALIDATE_EMAIL); } if(isset($_POST['visitor_phone'])) { $visitor_phone = filter_var($_POST['visitor_phone'], FILTER_SANITIZE_NUMBER_INT); } if(isset($_POST['total_adults'])) { $total_adults = filter_var($_POST['total_adults'], FILTER_SANITIZE_NUMBER_INT); } if(isset($_POST['total_children'])) { $total_children = filter_var($_POST['total_children'], FILTER_SANITIZE_NUMBER_INT); } if(isset($_POST['checkin'])) { $checkin_date = filter_var($_POST['checkin'], FILTER_SANITIZE_NUMBER_INT); } if(isset($_POST['checkout'])) { $checkout_date = filter_var($_POST['checkout'], FILTER_SANITIZE_NUMBER_INT); } if(isset($_POST['room_preference'])) { $room_type = filter_var($_POST['room_preference'], FILTER_SANITIZE_STRING); } if(isset($_POST['visitor_message'])) { $visitor_message = htmlspecialchars($_POST['visitor_message']); } $recipient = "[email protected]"; $headers = 'MIME-Version: 1.0' . "rn" .'Content-type: text/html; charset=utf-8' . "rn" .'From: ' . $visitor_email . "rn"; $email_content = "<html><body>"; $email_content .= "<table style='font-family: Arial;'><tbody><tr><td style='background: #eee; padding: 10px;'>Visitor Name</td><td style='background: #fda; padding: 10px;'>$visitor_name</td></tr>"; $email_content .= "<tr><td style='background: #eee; padding: 10px;'>Visitor Email</td><td style='background: #fda; padding: 10px;'>$visitor_email</td></tr>"; $email_content .= "<tr><td style='background: #eee; padding: 10px;'>Visitor Phone</td><td style='background: #fda; padding: 10px;'>$visitor_phone</td></tr>"; $email_content .= "<tr><td style='background: #eee; padding: 10px;'>Total Adults</td><td style='background: #fda; padding: 10px;'>$total_adults</td></tr>"; $email_content .= "<tr><td style='background: #eee; padding: 10px;'>Total Children</td><td style='background: #fda; padding: 10px;'>$total_children</td></tr>"; $email_content .= "<tr><td style='background: #eee; padding: 10px;'>Check-in Date</td><td style='background: #fda; padding: 10px;'>$checkin_date</td></tr>"; $email_content .= "<tr><td style='background: #eee; padding: 10px;'>Check-out Date</td><td style='background: #fda; padding: 10px;'>$checkout_date</td></tr>"; $email_content .= "<tr><td style='background: #eee; padding: 10px;'>Room Type</td><td style='background: #fda; padding: 10px;'>$room_type</td></tr></tbody></table>"; $email_content .= "<p style='font-family: Arial; font-size: 1.25rem;'><strong>Special Request from $visitor_name —</strong><i> $visitor_message</i>.</p>"; $email_content .= '</body></html>'; echo $email_content; if(mail($recipient, "Hotel Room Reservation Confirmation", $email_content, $headers)) { echo '<p>Thank you for booking a hotel room with us. We hope you have a pleasant stay.</p>'; } else { echo '<p>We are sorry but the booking confirmation email did not go through.</p>'; } } else { echo '<p>Something went wrong</p>'; } ?>
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 rooms 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 filled out by people. 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 form 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.