PHP Contact Form

Last modified on July 12th, 2018 by Vincy.

A contact form is an essential tool in converting a user into a customer. The contact form initiates a cold conversation with your user and who may become a client in the future. Importance of the best contact form on a website is almost always undermined. Building a contact form in PHP is easy but building it right is critical.

Check out the simple secure spam-free contact form in PHP – Iris. This is designed with conversion as the primary goal and it is not just about sending an email. It is the best PHP contact form available online, check it out!

PHP Contact Form

In this tutorial, we are having a contact form to let the user send their queries, clarifications, feedback and more details. In this contact form example, there two PHP files handling the submitted form fields in two different ways. In the index.php the posted contact form data are stored in the database. In the send_contact_mail.php file, I have created PHP code to send an email containing the submitted contact information.

Create Contact Form User Interface

The contact form UI with the Name, Email, Subject and Content fields can be shown to the user by using this HTML code. If you are looking for a responsive contact form UI, check the article. In this contact form HTML code, the UI is kept as simple as possible as the focus is on demonstrating the functionality of sending an email or storing the information in the database.

It includes jQuery form validation script to return validation directive with the boolean value. If the validation function returns true, then the form will be submitted to the PHP. Otherwise, the corresponding validation messages are shown in the form to let the user what is wrong with the form data they have submitted.

<html>
<head>
<title>Contact Us Form</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
    <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>
                <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>

    <script src="https://code.jquery.com/jquery-2.1.1.min.js"
        type="text/javascript"></script>
    <script type="text/javascript">
        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>
</body>
</html>

Read and Handle Contact Form Input in PHP

In the contact form template, the form tag is specified with the request method POST. On successful form submit after jQuery validation, the PHP code accesses the form data by using $_POST request method.

The index.php and send_contact_mail.php PHP files are used to handle the contact form data to store into the database and to send via an email, respectively. Both of these PHP files use the same contact form template created with the contact-view.php file.

Sending Contact Form Input Data via an Email

In this PHP code, the contact form data are received by using $_POST PHP superglobal. Those data are used to set the mail header and body and set with the PHP mail function. Once the email is sent to the recipient then the success message is shown in the contact form UI to acknowledge the user.

<?php
if(!empty($_POST["send"])) {
	$name = $_POST["userName"];
	$email = $_POST["userEmail"];
	$subject = $_POST["subject"];
	$content = $_POST["content"];

	$toEmail = "admin@phppot_samples.com";
	$mailHeaders = "From: " . $name . "<". $email .">\r\n";
	if(mail($toEmail, $subject, $content, $mailHeaders)) {
	    $message = "Your contact information is received successfully.";
	    $type = "success";
	}
}
require_once "contact-view.php";
?>

Storing Contact Form data into the Database

This PHP code helps you to store the contact form data into the database. Create a database table tbl_content with the name, email and more columns corresponding to our contact form fields. After getting the form data in the PHP, they will be used to form the MySQL INSERT statement. By executing the INSERT statement, the contact form data will be stored in the database. The following code implements the MySQL database connection and accesses the database to insert contact information. After the successful database insert the $message variable is set accordingly.

<?php
$conn = mysqli_connect("localhost", "root", "test", "blog_samples") or die("Connection Error: " . mysqli_error($conn));
mysqli_query($conn, "INSERT INTO tblcontact (user_name, user_email,subject,content) VALUES ('" . $name. "', '" . $email. "','" . $subject. "','" . $content. "')");
$insert_id = mysqli_insert_id($conn);
if(!empty($insert_id)) {
$message = "Your contact information is saved successfully";
?>

After executing the above insert query, the contact data will be added to the database table as,

mysql_contact_table

PHP Contact Form Output

This screenshot shows the output of the PHP contact form template. On this form submission,  the form fields are validated and the validation response messages are displayed next to the form field label. After successful PHP processing on the contact form data, the success message will be shown at the bottom of this form template.

PHP-Contact-Form-Output

Download

This PHP code tutorial was published on July 17, 2013.

↑ Back to Top

Share this Article