This content originally appeared on Envato Tuts+ Tutorials and was authored by Monty Shokeen
No matter what type of website you own or manage, you probably need a contact form. The contact form can help your visitors request a quote, ask for information, or share any tips or problems they're facing while using your website.
In this tutorial, our focus will be on creating a fully functional contact form in PHP from beginning to end. We'll begin with the markup of all the fields that we need to add and the basic styling of the contact form. After that, we'll move on to the PHP code to implement its functionality.
Of course, the easiest way to create a contact form is to download a professional contact form script from CodeCanyon.
But if you want to learn about how a contact form is created, read on! It might just be easier than you think.
Markup of Our HTML Contact Form
The first step towards creating our own contact form is to code the markup. We'll start doing that once we have a list of all the elements that we want inside our form. We'll need an input field for the name of the person who is contacting us, and we'll need a field for their email address so that we can reply to them if the need arises. We'll also need an input field for the reason people are contacting you and a textarea
where users can type their message.
If the website you're managing is very popular, you'll be getting a lot of emails through the contact form. To make sure that the right people get to read those emails and respond quickly, you need a couple more fields. For instance, you could add a field that can determine which department the visitor wants to contact, like marketing, support, or billing. This information can later be used to route the email appropriately. Ultimately, that might help you reply more quickly and sort the emails more efficiently.
How many fields you add to the contact form depends on the type of website you run, but make sure you don't overdo it. Forcing visitors to fill out too many details might discourage them from contacting you altogether.
Let's write the HTML code to add all the fields I just mentioned into our contact form.
<form action="contact.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-Z\sa-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="john.doe@email.com" required> </div> <div class="elem-group"> <label for="department-selection">Choose Concerned Department</label> <select id="department-selection" name="concerned_department" required> <option value="">Select a Department</option> <option value="billing">Billing</option> <option value="marketing">Marketing</option> <option value="technical support">Technical Support</option> </select> </div> <div class="elem-group"> <label for="title">Reason For Contacting Us</label> <input type="text" id="title" name="email_title" required placeholder="Unable to Reset my Password" pattern=[A-Za-z0-9\s]{8,60}> </div> <div class="elem-group"> <label for="message">Write your message</label> <textarea id="message" name="visitor_message" placeholder="Say whatever you want." required></textarea> </div> <button type="submit">Send Message</button> </form>
Before proceeding any further, I'd like to quickly summarize the meaning of some important attributes in the above markup. The action
attribute in the form determines where the form data needs to be sent. If you don't have an action
attribute, the data is sent back to the same URL. Here we've used contact.php, so the form data will be sent to that script.
The name
attribute for different input elements in the form is used to access the element values on the server side. For example, in the above form, you can get the name of the visitor contacting you using $_POST['visitor_name']
in contact.php.
We use the placeholder
attribute to give users a basic idea of the expected input for each field in the form. The required
attribute ensures that no important field is left blank before the user hits the submit button on the form.
The pattern
attribute is used to enforce some rules on the kinds of values that can go inside certain fields. In our case, we only allow users to use letters and the space character in the names they submit. We also limit the total number of acceptable characters to anything from 3 to 20 inclusive. The pattern that you use will depend on the type of input that you want from users.
The following CodePen demo shows us what our simple contact form PHP looks like with the above markup and a little bit of CSS.
Making Our HTML Contact Form Functional Using PHP
Right now, our PHP contact form doesn't do anything useful. Visitors can fill it out and hit the send message button, but we won't receive anything because there is no server-side code to handle the information provided by the form. In this section, we'll make our custom contact form functional using PHP.
Begin by creating a contact.php file and putting the following code inside it.
<?php if($_POST) { $visitor_name = ""; $visitor_email = ""; $email_title = ""; $concerned_department = ""; $visitor_message = ""; $email_body = "<div>"; if(isset($_POST['visitor_name'])) { $visitor_name = filter_var($_POST['visitor_name'], FILTER_SANITIZE_STRING); $email_body .= "<div> <label><b>Visitor Name:</b></label> <span>".$visitor_name."</span> </div>"; } 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); $email_body .= "<div> <label><b>Visitor Email:</b></label> <span>".$visitor_email."</span> </div>"; } if(isset($_POST['email_title'])) { $email_title = filter_var($_POST['email_title'], FILTER_SANITIZE_STRING); $email_body .= "<div> <label><b>Reason For Contacting Us:</b></label> <span>".$email_title."</span> </div>"; } if(isset($_POST['concerned_department'])) { $concerned_department = filter_var($_POST['concerned_department'], FILTER_SANITIZE_STRING); $email_body .= "<div> <label><b>Concerned Department:</b></label> <span>".$concerned_department."</span> </div>"; } if(isset($_POST['visitor_message'])) { $visitor_message = htmlspecialchars($_POST['visitor_message']); $email_body .= "<div> <label><b>Visitor Message:</b></label> <div>".$visitor_message."</div> </div>"; } if($concerned_department == "billing") { $recipient = "billing@domain.com"; } else if($concerned_department == "marketing") { $recipient = "marketing@domain.com"; } else if($concerned_department == "technical support") { $recipient = "tech.support@domain.com"; } else { $recipient = "contact@domain.com"; } $email_body .= "</div>"; $headers = 'MIME-Version: 1.0' . "\r\n" .'Content-type: text/html; charset=utf-8' . "\r\n" .'From: ' . $visitor_email . "\r\n"; if(mail($recipient, $email_title, $email_body, $headers)) { echo "<p>Thank you for contacting us, $visitor_name. You will get a reply within 24 hours.</p>"; } else { echo '<p>We are sorry but the email did not go through.</p>'; } } else { echo '<p>Something went wrong</p>'; } ?>
We have already done some client-side validation of user input. However, it's always safer to do server-side validation as well. We use the filter_var()
function to sanitize the name provided by the user. In a similar fashion, we also sanitize the value of $email_title
and $concerned_department
. You can use the filter_var()
function to validate or sanitize all types of user input. We also use the htmlspecialchars()
function to encode all the special HTML characters in the visitor message sent to us.
The value of $recipient
is based on the value of the variable $concerned_department
. This way, we make sure that only people who are actually supposed to look into the matter receive the email.
Also, we've used the $email_body
variable to format the email body which will be the main content of the email. As we are sending an email in the HTML format, we've used HTML to format the email body content.
Finally, we use the mail()
function to send an email which includes the information the visitor wanted us to know. Upon successful delivery of the email, we let the visitors know that we have received their email and that they'll be contacted soon.
Security is paramount when you're dealing with user data or input. Whether you should validate or sanitize the user input depends on what the input is and how you want to use it.
Validation simply checks if the user input follows a certain set of rules. For example, validation could check that the name of a person does not contain any numbers.
Sanitization is used to remove any offending characters that pose a security risk. For example, a malicious user trying to contact you through the form might add a script
tag in the textarea
to get you to download a harmful script. This is particularly worrisome when your website has public forums accessible by everyone.
However, you have to be very careful when getting rid of unwanted characters in user input. For example, you might decide to use filter_var($user_input, FILTER_SANITIZE_STRING);
on some input to strip all tags and encode special characters. However, this flag also strips harmless character input by legitimate users. Here is an example:
<?php $string = 'One of your posts about inequalities mentioned that when x < y and y < z then x < z.'; // Output: One of your posts about inequalities mentioned that when x echo filter_var($string, FILTER_SANITIZE_STRING); // Output: One of your posts about inequalities mentioned that when x < y and y < z then x < z. echo htmlspecialchars($string); ?>
If your website has a lot of maths-related topics, it will be relatively common for users to write < or > in contact forms or forum posts. Using the FILTER_SANITIZE_STRING
flag with the filter_var()
function will strip necessary information from the message in this case.
The point I am trying to make is that even though you should always validate or sanitize user data, make sure that you're not stripping away crucial information in the process.
Top 5 Simple Contact Form PHP Scripts From CodeCanyon
The above tutorial is worth going through as learning how to create a simple PHP contact form is a useful skill. But if you're crunched for time or just want to explore your options, check out these custom contact form PHP templates. They're professional quality and are featured on CodeCanyon:
1. Quform—Responsive Ajax Contact Form
Quform is a simple and responsive PHP email contact form example. This template is easy-to-use and works on a number of device screen sizes. It's sleek and works without needing to reload. It's a step that saves your users time, making it easier for them to fill out your form. Check out the rest of the Quform features from the item page.
2. PHP Form Builder
Are you looking to create a web contact form in PHP? Then it doesn't get much easier than with PHP Form Builder. The download includes a drag-and-drop form generator, making the creating process easier than ever. It's perfect for PHP beginners and experienced programmers and web developers. The list of forms you can make with this single download is long, making this a one-stop-shop for all your needs.
3. Easy Forms: Advanced Form Builder and Manager
Of course, Easy Forms rivals other simple contact form PHP templates in its plainness. It also features a drag-and-drop form builder with a modern UI. It's kind to beginners as well as experts on a time crunch. You can create a form in PHP and publish it anywhere, including WordPress, Drupal, or on static HTML web pages.
4. Just Forms Full
What this script's name says is exactly what you get. It's a comprehensive package of PHP forms that are ready for the web. You won't need any special knowledge of coding to get this download working. Just know the fields you want and start building. It's excellent for anyone looking to create a web form in PHP.
5. Easy PHP Contact Form Script
We round out our list with Easy PHP. This is a simple contact form PHP template that many variations. In this download, you'll get these contact forms and a whole lot more:
- contact form with CAPTCHA
- form with phone validation
- contact form with multiple text areas
Find More Time Saving PHP Templates
If you're interested in professional-quality PHP form scripts that you can start using on your site today, check out some of our other posts. You'll find even more useful options that you can customize quickly to save you precious time:
20 Best PHP Email Forms
18 Best Contact Form PHP Scripts for 2021
17 PHP Login and Registration Forms to Download
33 Most Useful PHP Scripts (And 5 Great Free Scripts)
Learn More About PHP And Coding With Envato Tuts+
Coding is a deep topic that takes a lot of time to master. If you don't have the right resources, it's easy to get frustrated and give up. That's why Envato Tuts+ has excellent coding courses, tutorials, and guides led by experienced instructors.
Want to dive further into PHP? Then have a look at these tutorials on the scripting language:
- PHPCreate a PHP Login Form
- PHPPHP Namespace Tutorial: The Basics
- PHPSearch and Replace Strings With Regular Expressions in PHP
- PHPUnderstanding Variable Scope in PHP
Final Thoughts
Creating a basic contact form in PHP is pretty simple. You begin by writing the HTML needed to create input elements for information like the user's name, email address, phone number, etc. The next step is writing CSS to make sure the contact form blends in perfectly with the rest of the website. The final step involves writing the PHP code that will take the information from the contact form and securely mail it to you.
The aim is to make sure that different form elements are laid out in a way that does not confuse people and the user input is sanitized and validated before you mail it to concerned parties. If all this is new to you or if you don't want to spend a lot of time creating a professional-looking contact form, you should definitely check out these top-rated contact form PHP scripts.
If you have any questions, feel free to let me know in the comments. My next tutorial will show you how to implement your own CAPTCHA to help keep contact form spam in check.
This content originally appeared on Envato Tuts+ Tutorials and was authored by Monty Shokeen
Monty Shokeen | Sciencx (2021-04-15T14:23:51+00:00) Create a Contact Form in PHP. Retrieved from https://www.scien.cx/2021/04/15/create-a-contact-form-in-php/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.