PHP Contact Form with Custom Fields

Last modified on December 17th, 2018 by Vincy.

Building a flexible PHP contact form is critical to your website’s conversion. Contact form is one of the most important pages in a website. It is the one that helps to covert a casual user to a customer. It should be hand crafted with at most care and it is not just another page in your website.

Check Iris, if you are looking for a professionally designed, simple, secure spam free contact form in PHP. Iris is developed with conversion as an objective and it will improve your submission rate percentage for sure.

Contact forms usually have the fields like subject, message sometimes user’s name who want to contact us via the PHP Contact form. These fields will change based on the website domain and needs. Sometimes it may not be good to restrict the contact form with a limited input fields set.

To help you in that situation, here I present you the code to create a PHP contact form with custom fields. In this tutorial, we are going to see how to make an option to add dynamic input fields to the contact form.

PHP Contact Form with Custom Fields

View Demo

In this example, I have created a PHP contact form with the name, email, subject and message fields. All these fields are required to be entered by the user before submitting this form. The form field validation is done in client-side by using jQuery.

The custom input fields are of a name-value pair. Initially, a single set of custom name-value pair of input fields will be displayed with an add-more option. By clicking the add-more option the custom fields could be added dynamically to the contact form.

PHP Contact Form HTML Interface

In this section, it shows the HTML code to display the PHP contact form with custom input fields. This code shows the standard contact form fields like email, subject and message with custom inputs. This contains an add more option to add more custom fields. In a previous tutorial, we have seen a PHP contact form example with an option to add multiple attachments.

In the below code, the jQuery functions are called to validate the form fields. All the fields except the custom fields are validated by using the JavaScript function. The add-more button control click event is mapped with the addMore() jQuery function. This function dynamically loads input field to the form container.

<div class="form-container">
    <form name="frmContact" id="" frmContact"" method="post" action=""
        enctype="multipart/form-data"
        onsubmit="return validateContactForm()">

        <div class="input-row">
            <label style="padding-top: 20px;">Name</label> <span
                id="userName-info" class="info"></span><br /> <input
                type="text" class="input-field" name="userName"
                id="userName" />
        </div>
        <div class="input-row">
            <label>Email</label> <span id="userEmail-info" class="info"></span><br />
            <input type="text" class="input-field" name="userEmail"
                id="userEmail" />
        </div>
        <div class="input-row">
            <label>Subject</label> <span id="subject-info" class="info"></span><br />
            <input type="text" class="input-field" name="subject"
                id="subject" />
        </div>
        <div class="input-row">
            <label>Message</label> <span id="userMessage-info"
                class="info"></span><br />
            <textarea name="content" id="content" class="input-field"
                cols="60" rows="6"></textarea>
        </div>
        <div id="custom-box">
            <label>Custom Fields</label>
            <div id="custom-input-container">
                <div class="input-row">
                    <input type="text" class="custom-input-field"
                        name="custom_name[]" /> <input type="text"
                        class="custom-input-field float-right"
                        name="custom_value[]" />
                </div>
            </div>
            <input type="button" class="btn-add-more" value="Add More"
                onClick="addMore()" />
        </div>

        <div>
            <input type="submit" name="send" class="btn-submit"
                value="Send" />

            <div id="statusMessage"> 
                        <?php
                        if (! empty($message)) {
                            ?>
                            <p class='<?php echo $type; ?>Message'><?php echo $message; ?></p>
                        <?php
                        }
                        ?>
                    </div>
        </div>
    </form>
</div>

jQuery Script to Add More Fields to Contact Form

Below simple jQuery script is used to add custom fields dynamically to the contact form. In this script, it loads the PHP file input.php. This file contains the custom fields HTML source. The name and value input for the custom fields are loaded dynamically by using this jQuery function. It uses the jQuery append function to insert the dynamic content to the custom field container.

This script also contains the form validation function validateContactForm(). This function will validate all the contact form fields except the custom inputs. Once this validation returns true, then the form will be posted to the PHP with custom field data.

In this example, I have used normal form submit without AJAX. If you are looking for a PHP contact form code with AJAX, the linked article will be useful for you. 

<script src="https://code.jquery.com/jquery-2.1.1.min.js"
    type="text/javascript"></script>
<script type="text/javascript">
    function addMore() {
    	   $("<DIV>").load("input.php", function() {
    	      $("#custom-input-container").append($(this).html());
    	   });	
    	}
    function validateContactForm() {
        var valid = true;

        $(".info").html("");
        $(".input-field").css('border', '#e0dfdf 1px solid');
        var userName = $("#userName").val();
        var userEmail = $("#userEmail").val();
        var subject = $("#subject").val();
        var content = $("#content").val();
        
        if (userName == "") {
            $("#userName-info").html("Required.");
            $("#userName").css('border', '#e66262 1px solid');
            valid = false;
        }
        if (userEmail == "") {
            $("#userEmail-info").html("Required.");
            $("#userEmail").css('border', '#e66262 1px solid');
            valid = false;
        }
        if (!userEmail.match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/))
        {
            $("#userEmail-info").html("Invalid Email Address.");
            $("#userEmail").css('border', '#e66262 1px solid');
            valid = false;
        }

        if (subject == "") {
            $("#subject-info").html("Required.");
            $("#subject").css('border', '#e66262 1px solid');
            valid = false;
        }
        if (content == "") {
            $("#userMessage-info").html("Required.");
            $("#content").css('border', '#e66262 1px solid');
            valid = false;
        }
        return valid;
    }
</script>

HTML Source for the Custom Input Fields

This is the input.php code which will be loaded dynamically to the form container. This code contains the input fields to get the custom field name-value pair. These are the HTML array input to contain an array of custom name-value added by the user.

<div class="input-row">
    <input type="text" class="custom-input-field"
        name="custom_name[]" /> <input type="text"
        class="custom-input-field float-right"
        name="custom_value[]" />
</div>

Code to Send PHP Contact Form Email with Custom Fields

After posting the contact form on successful validation, the posted values are received in the PHP endpoint. In this example, the PHP code will receive the post data for name, email, subject, message and the array of custom field data with custom-name and custom-value index.

Below code shows how to get the array of custom-name and custom-value post data to send the PHP contact form email. The email content is built by using the contact form data. The PHP mail function is used in this example. If you want to send the contact form email using Gmail SMTP then integrate external libraries like PHPMailer with your application.

if(!empty($_POST["send"])) {
    $name = $_POST["userName"];
    $email = $_POST["userEmail"];
    $subject = $_POST["subject"];
    $emailContent = "<p>You have received new email via Contact Form: </p>";
    $emailContent .=  "<p><b>Message: </b>" . $_POST["content"] . "</p>";
    
    if(!empty($_POST["custom_name"][0])) {
        $emailContent .= "<p><u>Custom Information:</u></p>";
        foreach($_POST["custom_name"] as $k=>$v) {
            $emailContent .=  "<p>" . $_POST["custom_name"][$k] . ": " . $_POST["custom_value"][$k] . "</p>";
        }
    }
    
    $toEmail = "admin@phppot_samples.com";
    $mailHeaders = "From: " . $name . "<". $email .">\r\n";
    if(mail($toEmail, $subject, $emailContent, $mailHeaders)) {
        $message = "Your contact information is received successfully.";
        $type = "success";
    }
}

PHP Contact Form with Custom Fields Output

The screenshot shows the output of the PHP contact form with the custom fields and the add-more option.

PHP Contact Form with Custom Fields Output

View DemoDownload

↑ Back to Top

Share this Article