1. Code
  2. PHP
  3. PHP Scripts

Create a Contact Form in PHP

Scroll to top

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.

1
<form action="contact.php" method="post">
2
  <div class="elem-group">
3
    <label for="name">Your Name</label>
4
    <input type="text" id="name" name="visitor_name" placeholder="John Doe" pattern=[A-Z\sa-z]{3,20} required>
5
  </div>
6
  <div class="elem-group">
7
    <label for="email">Your E-mail</label>
8
    <input type="email" id="email" name="visitor_email" placeholder="john.doe@email.com" required>
9
  </div>
10
  <div class="elem-group">
11
    <label for="department-selection">Choose Concerned Department</label>
12
    <select id="department-selection" name="concerned_department" required>
13
        <option value="">Select a Department</option>
14
        <option value="billing">Billing</option>
15
        <option value="marketing">Marketing</option>
16
        <option value="technical support">Technical Support</option>
17
    </select>
18
  </div>
19
  <div class="elem-group">
20
    <label for="title">Reason For Contacting Us</label>
21
    <input type="text" id="title" name="email_title" required placeholder="Unable to Reset my Password" pattern=[A-Za-z0-9\s]{8,60}>
22
  </div>
23
  <div class="elem-group">
24
    <label for="message">Write your message</label>
25
    <textarea id="message" name="visitor_message" placeholder="Say whatever you want." required></textarea>
26
  </div>
27
  <button type="submit">Send Message</button>
28
</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.

1
<?php
2
 
3
if($_POST) {
4
    $visitor_name = "";
5
    $visitor_email = "";
6
    $email_title = "";
7
    $concerned_department = "";
8
    $visitor_message = "";
9
    $email_body = "<div>";
10
     
11
    if(isset($_POST['visitor_name'])) {
12
        $visitor_name = filter_var($_POST['visitor_name'], FILTER_SANITIZE_STRING);
13
        $email_body .= "<div>

14
                           <label><b>Visitor Name:</b></label>&nbsp;<span>".$visitor_name."</span>

15
                        </div>";
16
    }
17
18
    if(isset($_POST['visitor_email'])) {
19
        $visitor_email = str_replace(array("\r", "\n", "%0a", "%0d"), '', $_POST['visitor_email']);
20
        $visitor_email = filter_var($visitor_email, FILTER_VALIDATE_EMAIL);
21
        $email_body .= "<div>

22
                           <label><b>Visitor Email:</b></label>&nbsp;<span>".$visitor_email."</span>

23
                        </div>";
24
    }
25
     
26
    if(isset($_POST['email_title'])) {
27
        $email_title = filter_var($_POST['email_title'], FILTER_SANITIZE_STRING);
28
        $email_body .= "<div>

29
                           <label><b>Reason For Contacting Us:</b></label>&nbsp;<span>".$email_title."</span>

30
                        </div>";
31
    }
32
     
33
    if(isset($_POST['concerned_department'])) {
34
        $concerned_department = filter_var($_POST['concerned_department'], FILTER_SANITIZE_STRING);
35
        $email_body .= "<div>

36
                           <label><b>Concerned Department:</b></label>&nbsp;<span>".$concerned_department."</span>

37
                        </div>";
38
    }
39
     
40
    if(isset($_POST['visitor_message'])) {
41
        $visitor_message = htmlspecialchars($_POST['visitor_message']);
42
        $email_body .= "<div>

43
                           <label><b>Visitor Message:</b></label>

44
                           <div>".$visitor_message."</div>

45
                        </div>";
46
    }
47
     
48
    if($concerned_department == "billing") {
49
        $recipient = "billing@domain.com";
50
    }
51
    else if($concerned_department == "marketing") {
52
        $recipient = "marketing@domain.com";
53
    }
54
    else if($concerned_department == "technical support") {
55
        $recipient = "tech.support@domain.com";
56
    }
57
    else {
58
        $recipient = "contact@domain.com";
59
    }
60
     
61
    $email_body .= "</div>";
62
63
    $headers  = 'MIME-Version: 1.0' . "\r\n"
64
    .'Content-type: text/html; charset=utf-8' . "\r\n"
65
    .'From: ' . $visitor_email . "\r\n";
66
     
67
    if(mail($recipient, $email_title, $email_body, $headers)) {
68
        echo "<p>Thank you for contacting us, $visitor_name. You will get a reply within 24 hours.</p>";
69
    } else {
70
        echo '<p>We are sorry but the email did not go through.</p>';
71
    }
72
     
73
} else {
74
    echo '<p>Something went wrong</p>';
75
}
76
?>

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:

1
<?php
2
 
3
$string = 'One of your posts about inequalities mentioned that when x < y and y < z then x < z.';
4
 
5
// Output: One of your posts about inequalities mentioned that when x 

6
echo filter_var($string, FILTER_SANITIZE_STRING);
7
 
8
// Output: One of your posts about inequalities mentioned that when x &lt; y and y &lt; z then x &lt; z.

9
echo htmlspecialchars($string);
10
 
11
?>

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.