PHP Contact Form

Last modified on December 17th, 2018 by Vincy.

A contact form is an essential tool in converting a user into a customer. In this article, you will get a free PHP contact form script that can be used in your website. It is responsive and will work seamlessly in mobile, tablet and other devices.

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

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 PHP contact form is easy but building it right is critical.

PHP Contact Form

In this tutorial, we are having a PHP 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 script, 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.

Contact Form User Interface

The PHP contact form UI with the Name, Email, Subject and Content fields can be shown to the user by using this HTML script. If you are looking for a responsive contact form UI, check the article. In this 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>PHP Contact 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>

PHP Contact Form Input Processing

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

A contact form always faces spam issues. There are numerous autonomous bots that scans the web regularly looking for forms and in particular contact forms to submit spam information. In the spam content, there will be mostly links to legitimate sites trying to promote them. There are two ways to block those spams, one by custom script implementing honeypot and related logic, second by using captcha implementation like Google reCaptcha. Iris is a contact form that has both the option implemented. If you are looking to implement the captcha yourself, check the PHP contact form with Google reCAPTCHA article.

The index.php and send_contact_mail.php PHP files are used to handle the PHP 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.

Send 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. You can send email using PHPMailer package and refer send email in PHP using Gmail SMTP server.

<?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";
?>

Store Contact Form data into the Database

This PHP code helps you to store the PHP 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

↑ Back to Top

Share this Article