PHP Contact Form

by Vincy. Last modified on September 20th, 2023.

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 on your website. It is responsive and will work seamlessly on mobile, tablet and other devices.
View Demo

The contact form initiates a cold conversation with your user and who may become a client in the future. The 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 are 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.

PHP-Contact-Form-Output

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 a jQuery form validation script to return the 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>
	<!-- include JavaScript validation here -->
</body>
</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;
}

PHP Contact Form Input Processing

In the contact form template, the form tag is specified with the request method POST. On successful form submission 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 scan 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, and second by using captcha implementation like Google reCaptcha.

If you are looking to implement the captcha yourself, check the PHP contact form with the Google reCAPTCHA article.

The index.php and send_contact_mail.php PHP files are used to handle the PHP contact form data to store in the database and to send via 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 the PHPMailer package and refer to send email in PHP using the Gmail SMTP server.

<?php

function strip_crlf($string)
{
    return str_replace("\r\n", "", $string);
}

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

    $toEmail = "admin@phppot_samples.com";
    // CRLF Injection attack protection
    $name = strip_crlf($name);
    $email = strip_crlf($email);
    if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "The email address is invalid.";
    } else {
        // appending \r\n at the end of mailheaders for end
        $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 in the Database

This PHP code helps you to store the PHP contact form data in 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
if (! empty($_POST["send"])) {
    $name = $_POST["userName"];
    $email = $_POST["userEmail"];
    $subject = $_POST["subject"];
    $content = $_POST["content"];
    $conn = mysqli_connect("localhost", "root", "test", "contactform_database") or die("Connection Error: " . mysqli_error($conn));
    $stmt = $conn->prepare("INSERT INTO tblcontact (user_name, user_email, subject,content) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("ssss", $name, $email, $subject, $content);
    $stmt->execute();
    $message = "Your contact information is saved successfully.";
    $type = "success";
    $stmt->close();
    $conn->close();
}
require_once "contact-view.php";
?>

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

mysql_contact_table

Contact form database table structure

--
-- Database: `contactform_database`
--

-- --------------------------------------------------------

--
-- Table structure for table `tblcontact`
--

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;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tblcontact`
--
ALTER TABLE `tblcontact`
  ADD PRIMARY KEY (`contact_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tblcontact`
--
ALTER TABLE `tblcontact`
  MODIFY `contact_id` int(11) NOT NULL AUTO_INCREMENT;

View Demo Download

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”

  • Vincy says:

    Hi Pali,

    Thanks for your comment.

  • jitendra says:

    Great work!!!!!!

  • Vicky says:

    Its not working kindly mail me the data base detail so that i can define in my sql

    • Vincy says:

      Vicky, it is there available with the download.

      • Alexandre Carneiro says:

        Hi Vincy. Tehre’s no file like database.sql, to create a blank database with all the necessary fields and rows? Please advise.

      • Vincy says:

        Hi Alexadre,

        I have updated the article with the database table structure. Please use that.

  • AArthy says:

    Will the email be sent if i run the PHP script in localhost?

  • Hatim says:

    How to apply this code I try three time but not working plzz help me
    Kindly request

    • Vincy says:

      Hatim, let me know the error you are getting. This code is working good in many contact forms.

  • Kuldeep Bisht says:

    Hello, ma’am, I don’t know how to connect with the database can you help me, please.

    • Vincy says:

      Hi Kuldeep,

      To connect with the database the code is given in the article. It is easy, try that and let me know.

  • Constance Noble says:

    Please can you create an email campaign script for business?

  • Umesh Shakya says:

    Awesome Working
    Thanks

  • rafael says:

    I am testing this form but it is not sending to the email that I put in the code … it is connecting and recording in the bank, but it is not sending, you know what it can be?

    • Vincy says:

      Hi Rafael,

      You need to check your server mail configuration. This script uses PHP’s mail() function and your server should be configured to send mail. Otherwise, you need to update the code to use SMTP. It is available in another linked article and you can use that.

      • aleesha says:

        mail(): Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in E:\project\htdocs\novaesolution\contact_submit.php on line 68

        on trying it showing this error?how can i correct this

      • Vincy says:

        Hi Aleesha,

        You need to to configure your server to send email. The contact form requires that to send the email. Otherwise use smtp based option to send the email.

  • Angela says:

    Hi not working. Datas are added in database but i did not received any emails. I have seen no error. What happened?

  • Stanga Radu says:

    Beautiful explication, can you help me with the code for posting the information from the table into a html page?
    Best regards!

  • Saimado says:

    How to include this code on my site? please help me

    • Vincy says:

      Hi Saimado, you can download the code and it is free. Just download and make sure your server supports sending email. Thats it.

  • LAMALEM AZEDDINE says:

    thank you

  • Jecky says:

    Nice work. I love it

  • Steven Martinez says:

    Vincy,

    Im trying to learn and figure out PHP, this was very helpful. This might be a very basic/ stupid question but how would you implement the form validation if you would want for the form to both send and email and also store it in the database at the same time. Some of the code seems to be overlap but im having issues getting the two functions to work at the same time and Im not 100% sure how the different confirmation responses would be handled in a combined scenario either.

    • Vincy says:

      Hi Steven,

      There are two ways to handle validations. Regular way is to handle it in the front-end via JavaScript. Second way is to handle it in the server-side using PHP. It is better to have both the validations done. Having server-side validation as a fallback to client side.

      Step 1: Client side validation, if it passes submit the form and the control goes to server-side.
      Step 2: Server side validation, if it passes then move on to next step otherwise, respond back with error message.
      Step 3: Store the information in database.
      Step 4: Send email.

  • Tiwin says:

    SMTP Error: Could not connect to SMTP host. This is the error i got while running the code

    • Vincy says:

      Hi Twin,

      Check if your server is configured with SMTP support. It should be able to send email. From the message, I can infer that there is no support.

  • curtis says:

    am getting “Your contact information is saved successfully.”
    but neither the database showing records nor the email…help plz

  • aditya says:

    bro i tried 20 php form . but all of them only this one is working .

  • M Sufyan sheikh says:

    Hello,
    If it’s possible to use this form receiving data on my Gmail and also send the data that person who fills this form, In short, I want to recieve form message on my Gmail and also send it to the client.

    Thank You.

    • Vincy says:

      Hi Sheikh,

      Yes, it is possible. Give your Gmail as the recipient and also add the user’s email in CC, so that the contact form will send email to your Gmail and the user.

  • max says:

    HI Vincy,

    im beginner in this need a help.

    I just pasted the first set in index page, and need to know where to paste the second set code in different php file or same index itself. because i didn’t find any redirection like ( form action =”mail.php”)so kindly help.

    is it neccessity to add third set of code? and if yes where to add? what is contact-view.php?out of three which set of code to be written in contact-view.php?

  • Deepak Chauhan says:

    very useful

  • RK says:

    This is really good and awesome, Thank You so much VINCY…

  • Rakesh says:

    Hello Vincy, I have tried to implement the same code as above, the details collected through the form are being stored in the database but the email is not being sent. Could you help me out in finding where the problem could be?

  • Prashish says:

    I’m trying to add reset button, but not working.
    Can you please help me with it!

  • Nurul Isalm says:

    no sql file in this project

  • Luciano says:

    Does it work on a site on a folder of the root?

  • Yogesh Sharma says:

    Hi Vincy, Thanks for creating the awesome form with simple steps.

    It would be better you add an attachment feature as well. So that we can use the same for career form as well. If possible.

    Thanks in advance.

  • kaveesha says:

    please can i know that, from what name we should create the database in phpmyadmin? Also when we save to the c drive what is the name we should give for save?

  • Samim says:

    Now working.

  • JOJO says:

    I will try. thank you very much

  • thrilok says:

    not working

    “Connection Error:”

    • Vincy says:

      Hi Thrilok,

      You need to configure your server to send email to use the PHP’s mail() function or you have to use the SMTP option.

  • Daniel says:

    I haven’t tried your contact form yet, but it looks excellent. I have a problem with a form that I made on my own, when I receive the email, the name, email and the subject come to me blank, what could it be that I am doing wrong?

    • Vincy says:

      Hi Daniel,

      You need to post the problem (error details or trace) you are getting. Then I can help you out.

  • George says:

    Hello,

    We try to integrate your contact for but it does not encode correctly the Cyrillic. How can we make it work correctly.

  • Arham Tibrewal says:

    I was wondering if there are any errors in the code as it is showing that the code ends in an unexpected way for me

    • Vincy says:

      Hi Arham,

      This contact form is working good for many. If you can post the errors, I can help you out.

  • Tunde says:

    Great work. Vincy, this is helpful to me, thanks

  • Malenge 'Styles' Ngondo says:

    Good stuff, will give it a try

  • Moses says:

    It was perfectly done! Loved it

  • afrith says:

    sql file plz sent

    • Vincy says:

      Hi Afrith,

      I have updated the article with the database table structure. You can take it from the article.

  • Sunil Pandya says:

    Can you prepare a form that receives the email from the website viewer?

  • Russell says:

    data not store to database. Why?

  • Abhinav says:

    Works perfectly!

  • nazri says:

    how to make the content appear in whatsapp instead of email?

  • Saadallah Essadqi says:

    Thank you very much!! This is really helpful, your explanation here was more useful then a week of me listening to my teacher.

    • Vincy says:

      A teacher in a school or college is always the best and no substitute for that. But I take these words as a compliment and thank you.

  • Joe says:

    I find it amusing how some people are all like “Send it to me” like… “Bro.. you’re working for me now, you owe me everything”

    No thank you, no nothing, just asking for stuff…

    • Vincy says:

      Hi Joe,

      I got used to it. Digital space is like that. People do not feel that there is a person sitting behind all this. But some are so nice. We will get to experience both the ends :-)

  • Arvind Kumar says:

    can this form store emojis and special characters?

  • sami says:

    Hi Vincy

    Thank you for this code.

    Can you tell me about the part of sending the email in the code?

    I did not find any code call send_contact_mail.php

    also not send email with me just store in database.

  • Kamal says:

    Hi Vincy,

    I am havin a matrimony website and i want to add 3 piece of information in my website

    • Vincy says:

      Hi Kamal,

      Sure. If you are looking for my services, please send email to me and we can take things forward.

  • Innocent Cyril says:

    Please how will I make that page to apply to my website home page pls I need help

    • Vincy says:

      Hi Cyril,

      You can integrate this contact form as a separate page or also as a section of an existing page. The index.php page can be renamed as contact.php and integrated accordingly.

  • Zeynep says:

    Thank you for this usefull information.I have a problem. I don’t want to run this code in index.php. What can I do ? When I write in index.php my website main page will be index.php. I don’t want to do this.
    Thank you again :)

    • Vincy says:

      Hi Zeynep,

      Just rename the index.php to contact.php or something else that you wish. Then like the files accordingly. I you want a pretty url, then you can use htaccess and rewrite it.

  • Abhinay Recriwal says:

    Nice information

  • niharika says:

    A little bit of css of the contact form would make the tutorial complete..

  • Ray says:

    Hi and thank you for this info. I am getting a “Connection error”. I am using Host Gator and I’m pretty sure they support SMTP. Any thoughts/help?

    THank you

  • Salman Asghar says:

    Hello Vincy

    I am using this form on my new site but, not working. it is a Deshcore theme. Can you please help me?

    Salman Asghar

  • Mukesh says:

    can you create contact form for tourism
    selection round button ( Himachal , kashmir, uttarakhand, sikkim, kerala, international)
    Tour type round button ( Deluxe budget, Super deluxe, luxury)

    name
    mobile
    email

    Adult (1….20)
    Child 5yr above ( 0….10)
    Pick up
    pick up date
    Drop at
    drop date
    Message box

    • Vincy says:

      Hi Mukesh,

      You can customize this form to suit your needs. Or else you should hire a person to do this customization.

  • paterik4 says:

    Hi!

    I wrote my phpmailer with one php file and with a js file with ajax call, it send email well.

    I also wrote an another php file, that stores data to database well.

    But if i put them together, only email works.

    Can you help me?

    • Vincy says:

      Hi Paterik,

      I need to see the code to help you. Get in touch with me via my email.

  • Abdur Rahman says:

    Nice information

  • syed shahida begum says:

    it was helpfull.especially for the ones who fear looking into heavy code.

  • KArlo Dz says:

    How do you store email login data in a safely way? From what I see all the data is available in file but how do you protecting it from being compromised? Nobody wants to expose those sensitive data…

    • Vincy says:

      Hi Karlo,

      You can choose to encrypt and store the data. It depends on your use-case and needs.

  • SHIVAM SURI says:

    connection error plz help

  • James says:

    Thanks for the post.

  • Ricardo Da Rocha Martins says:

    On the form, the id for the name has 2 (“) either side of frmContact. Is that correct?

    • Vincy says:

      Hi Ricardo,

      The id can be empty or that attribute can be omitted. Or you can choose to name it. Everything is fine.

  • Oscar James says:

    Thanks for the great useful info.

  • Sanjeev says:

    Mail is not receiving.

    • Vincy says:

      This code uses the PHP’s mail() function to send the email. Your server needs to be configured to send the email.

  • Hamid says:

    Please how do i configure my server to send email. Am confused

  • Nathan Bendall says:

    I can’t get the data to save to my database, what should the table and database be called?

    • Vincy says:

      Hi Nathan,

      The database and table name can be anything you choose. Remember to use the same when you connect to the database and in the insert query.

  • Berk says:

    Vincy,
    Can this codes make it work contact form and newsletter in my HTML website? i am a beginner yet. lead the way. I can create database and table in PHPmyadmin on localhost. All these codes be saved in one php file?
    Many thanks

    • Vincy says:

      Hi Berk,

      Yes, it will work for contact form and can be used for newsletter also. You will need PHP support in your webserver and the website can be in HTML.

  • sreeram says:

    what is the database name we have o create in localhost ? as the database table name is ( tblcontact ) want to know about the name of the database.

    • Vincy says:

      Hi Sreeram,

      You can have any database name. Whatever name you keep should be used in the database connection details.

  • LASZLO BUZAS says:

    Koszi Pali :)

    the Comment box shoud me top of the comments ;)

  • Pratiksha says:

    It’s really one of the best contact form I found yet. Please clear my a doubt, it’s required mysql for database or not

Comments are closed.

↑ Back to Top

Share this page