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.
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;
}
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.
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";
?>
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,
--
-- 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;
Comments are closed.
Hi Pali,
Thanks for your comment.
good
nice topic
Great work!!!!!!
Thank you Jitendra.
Its not working kindly mail me the data base detail so that i can define in my sql
Vicky, it is there available with the download.
Hi Vincy. Tehre’s no file like database.sql, to create a blank database with all the necessary fields and rows? Please advise.
Hi Alexadre,
I have updated the article with the database table structure. Please use that.
Will the email be sent if i run the PHP script in localhost?
Yes Arthy, this will work in localhost also.
send email code php
Hi Tauffeque,
If you wish to use PHP’s mail() function to send email, use the code from this current article. If you want to send email using smtp, try using https://phppot.com/php/send-email-in-php-using-gmail-smtp/
How to apply this code I try three time but not working plzz help me
Kindly request
Hatim, let me know the error you are getting. This code is working good in many contact forms.
Hello, ma’am, I don’t know how to connect with the database can you help me, please.
Hi Kuldeep,
To connect with the database the code is given in the article. It is easy, try that and let me know.
Please can you create an email campaign script for business?
Sure Constance. I am working on it and will be soon added to the shop. Thanks.
Awesome Working
Thanks
Welcome Umesh.
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?
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.
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
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.
Hi not working. Datas are added in database but i did not received any emails. I have seen no error. What happened?
Angela, you should check your email configuration.
Beautiful explication, can you help me with the code for posting the information from the table into a html page?
Best regards!
Sure, get me in touch with me via email and I do provide freelance services.
How to include this code on my site? please help me
Hi Saimado, you can download the code and it is free. Just download and make sure your server supports sending email. Thats it.
thank you
Welcome Lamalem.
Nice work. I love it
Thank you Jecky.
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.
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.
SMTP Error: Could not connect to SMTP host. This is the error i got while running the code
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.
am getting “Your contact information is saved successfully.”
but neither the database showing records nor the email…help plz
Hi Curtis,
The server should be configured to send email for the contact form to work.
bro i tried 20 php form . but all of them only this one is working .
Thank you Aditya.
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.
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.
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?
Hi Max,
Yes you need to use the complete set of code for the contact form to function.
very useful
Thank you Deepak.
This is really good and awesome, Thank You so much VINCY…
Welcome RK.
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?
Hi Rakesh,
Is your server configured to send email otherwise you may have to use SMTP.
I’m trying to add reset button, but not working.
Can you please help me with it!
Hi Prashish,
Show me your script and lets check it out.
no sql file in this project
Hi Nurul,
The database sql structure is updated in the article.
Does it work on a site on a folder of the root?
Yes Luciano, it can work both on the root of the site or on a subfolder.
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.
Thank you Yogesh. Use this code https://phppot.com/php/send-email-with-multiple-attachments-using-php/ to send email via contact form with attachment
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?
Hi Kaveesha,
You can name the database anything. Just use “test” like given in the example.
Now working.
Thank you Samim.
I will try. thank you very much
Welcome Jojo.
not working
“Connection Error:”
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.
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?
Hi Daniel,
You need to post the problem (error details or trace) you are getting. Then I can help you out.
Hello,
We try to integrate your contact for but it does not encode correctly the Cyrillic. How can we make it work correctly.
Hi George,
Post the errors you are facing and sure I will attend to it.
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
Hi Arham,
This contact form is working good for many. If you can post the errors, I can help you out.
Great work. Vincy, this is helpful to me, thanks
Thank you Tunde.
Good stuff, will give it a try
Thank you Ngondo. Try and update the result in comments.
It was perfectly done! Loved it
Thank you Moses.
sql file plz sent
Hi Afrith,
I have updated the article with the database table structure. You can take it from the article.
Can you prepare a form that receives the email from the website viewer?
Hi Sunil,
The contact form is there in the website. Link to it is available in the top.
data not store to database. Why?
Hi Russell,
Check your database credentials, host and related configuration.
Works perfectly!
Thank you Abhinav.
how to make the content appear in whatsapp instead of email?
Hi Nazri,
You need to integrate WhatsAPP API for that!
Thank you very much!! This is really helpful, your explanation here was more useful then a week of me listening to my teacher.
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.
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…
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 :-)
can this form store emojis and special characters?
Hi Arvind,
Yes this contact form can store emojis and special characters.
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.
Hi Sami,
This uses PHP’s mail() function to send the contact mail.
Hi Vincy,
I am havin a matrimony website and i want to add 3 piece of information in my website
Hi Kamal,
Sure. If you are looking for my services, please send email to me and we can take things forward.
Please how will I make that page to apply to my website home page pls I need help
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.
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 :)
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.
Nice information
Thank you :-)
A little bit of css of the contact form would make the tutorial complete..
Yes Niharika, I agree with that. Updates are coming soon :-)
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
Hi Ray,
To send email using smtp, you can use this code https://phppot.com/php/send-email-in-php-using-gmail-smtp/
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
Sure Salman,
Get in touch with me via my email and we can take things forward.
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
Hi Mukesh,
You can customize this form to suit your needs. Or else you should hire a person to do this customization.
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?
Hi Paterik,
I need to see the code to help you. Get in touch with me via my email.
Nice information
Thank you Rahman.
it was helpfull.especially for the ones who fear looking into heavy code.
Thank you Syed.
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…
Hi Karlo,
You can choose to encrypt and store the data. It depends on your use-case and needs.
connection error plz help
Hi Suri,
You need to configure your server to send email.
Thanks for the post.
Welcome James.
On the form, the id for the name has 2 (“) either side of frmContact. Is that correct?
Hi Ricardo,
The id can be empty or that attribute can be omitted. Or you can choose to name it. Everything is fine.
Thanks for the great useful info.
Welcome and thank you James.
Mail is not receiving.
This code uses the PHP’s mail() function to send the email. Your server needs to be configured to send the email.
Please how do i configure my server to send email. Am confused
Hi Hamid,
It depends on which server you are using. Other option is to use SMTP based email and you may use PHPMailer to send the email. This article will help you https://phppot.com/php/send-email-in-php-using-gmail-smtp/
I can’t get the data to save to my database, what should the table and database be called?
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.
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
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.
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.
Hi Sreeram,
You can have any database name. Whatever name you keep should be used in the database connection details.
Koszi Pali :)
the Comment box shoud me top of the comments ;)
Ah, yes! I will move it up, thank you Laszlo.
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
Welcome Praiksha. Database is optional.