PHP Contact Form

by Vincy. Last modified on June 22nd, 2022.

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.

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 difficult.

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.

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.


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.

<title>PHP Contact Form</title>
<link rel="stylesheet" type="text/css" href="style.css" />
    <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 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 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 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>
                <input type="submit" name="send" class="btn-submit"
                    value="Send" />

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

    <script src=""
    <script type="text/javascript">
        function validateContactForm() {
            var valid = true;

            $(".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").css('border', '#e66262 1px solid');
                valid = false;
            if (userEmail == "") {
                $("#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").css('border', '#e66262 1px solid');
                valid = false;
            if (content == "") {
                $("#content").css('border', '#e66262 1px solid');
                valid = false;
            return valid;

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.

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.

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

	$toEmail = "";
	$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.

$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,


Contact form database table structure

CREATE TABLE `tblcontact` (
  `contact_id` int(11) NOT NULL,
  `user_name` varchar(100) NOT NULL,
  `user_email` varchar(255) NOT NULL,
  `subject` varchar(255) NOT NULL,
  `content` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;


Comments to “PHP Contact Form”

Leave a Reply

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

↑ Back to Top

Share this Article