7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
  1. Code
  2. PHP

Create a Contact Form in PHP

Scroll to top
Read Time: 11 mins

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.

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.

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:

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.

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 on the item page.

Quform Contact Form HTML PHPQuform Contact Form HTML PHPQuform Contact Form HTML PHP

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 process of creating forms 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.

PHP Form BuilderPHP Form BuilderPHP Form Builder

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.

Easy Forms Create Contact FormEasy Forms Create Contact FormEasy Forms Create Contact Form

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:

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:

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 contact us on Twitter. My next tutorial will show you how to implement your own CAPTCHA to help keep contact form spam in check. 

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.