PHP Contact Form with Custom Fields

by Vincy. Last modified on July 3rd, 2023.

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

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

View Demo

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

PHP Contact Form with Custom Fields Output

In this example, I have created a PHP contact form with the name, email, subject, and message fields. The user must enter all these fields before submitting this form. The form field validation is done on the client side by using jQuery.

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

PHP Contact Form HTML Interface

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 the 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. This script loads the PHP file input.php. This file contains the custom fields’ HTML source. The custom fields’ name and value input are loaded dynamically using this jQuery function. It uses the jQuery append function to insert the dynamic content into 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, the form will be posted to the PHP with custom field data.

In this example, I have used standard form submit without AJAX. If you are looking for a PHP contact form code with AJAX, the linked article will be helpful 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.

The 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";
    }
}

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “PHP Contact Form with Custom Fields”

  • AmrutaK says:

    I am looking for a condition in PHP to restrict the email field with business emails only. I want the email field should accept only business emails only. Can you please help me for this?

  • David says:

    Hi,

    This form looks great! I’m having a problem, though.

    I tried the demo and everything appears to work just fine but when I build the project and run it from my test site I don’t receive an email and I don’t get a success message. The form simply reloads.

    Thinking that I may have done something wrong I loaded your code intact (first using my email address, and then with no changes, just using your email address). Nothing changed. I still got no success message and didn’t receive the email on the test using my address.

    Do you have any idea why this might be?

    Thanks,
    David

    • Vincy says:

      Hi David,

      You should have emailing support enabled in your web-server and configured in your php.

  • Omary Kijogoo says:

    Hello!. Brother Help me I’want one to one chat system

  • Laszlo says:

    Hi!
    Great tutorials!
    But how to integrate php mail function?ű
    Because the script does not send me the e-mail.
    Please help me!
    Thanks!

    • Vincy says:

      Hi Laszlo,

      Your system should have a sendmail program and that should be configured with your Apache and PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page