The Contact Form is an essential element for almost every website. The contact us form allows visitors to communicate with the site owner from the website. Using the contact us form, visitors can easily submit their queries, views, opinions, and suggestions to the site administrator about the website, service, or product. Also, the submitted information can be sent to the site owner or administrator via email.
Contact form helps you receive queries from visitors and provide a quick response to them. The thought of a contact form is very simple; the user is able to send their query via email to the respective organization. In this tutorial, we’ll show you how to create a simple contact form with PHP and integrate it into your website. Using our PHP contact form script, you’ll be able to add a contact us form to your website within 5 minutes. The contact form not only submits, but also sends an email to you on every form submission using PHP.
In this example script, we will build a contact form with email functionality using PHP. For better understanding, we will divide the PHP contact form script into two parts: the HTML form and the submission code. You can place this code together on the web page where you want to display the contact us form widget.
Contact Form HTML:
Create an HTML form with some input elements (Name, Email, Subject, and Message).
type="submit" element to provide a submit button in the form.At the top of the contact form, display the form submission status message with PHP.
<!-- Status message -->
<?php if ($success): ?>
<div class="success-message"><?php echo $success; ?></div>
<?php else: ?>
<?php
$allErrors = array_filter($errors);
if (!empty($allErrors)) {
echo '<div class="error-message">';
foreach ($errors as $key => $msg) {
if ($msg && $key !== 'general') {
echo htmlspecialchars($msg) . "<br>";
}
}
if (!empty($errors['general'])) {
echo htmlspecialchars($errors['general']) . "<br>";
}
echo '</div>';
}
?>
<?php endif; ?>
<!-- Form fields -->
<form method="post" action="">
<div class="form-group">
<label for="name">Name</label>
<input
type="text"
name="name"
required
placeholder="Your Name"
value="<?php echo htmlspecialchars($_POST['name'] ?? ''); ?>">
</div>
<div class="form-group">
<label for="email">Email</label>
<input
type="email"
name="email"
required
placeholder="ex: your@email.com"
value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input
type="text"
name="subject"
required
placeholder="Subject of your request"
value="<?php echo htmlspecialchars($_POST['subject'] ?? ''); ?>">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea
name="message"
required
placeholder="Type your message here"><?php echo htmlspecialchars($_POST['message'] ?? ''); ?></textarea>
</div>
<input type="submit" name="submit" class="submit-btn" value="Send Message">
</form>
Contact Form Submission with PHP:
The following PHP code snippet handles the form submission process and email sending functionality.
Note: Place this code at the top of the web page before the HTML form code.
<?php
$success = '';
$errors = [];
// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
// Sanitize inputs
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$subject = trim($_POST['subject'] ?? '');
$message = trim($_POST['message'] ?? '');
// Validate inputs
if (empty($name)) {
$errors['name'] = "Please enter your name.";
}
if (empty($email)) {
$errors['email'] = "Please enter your email address.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = "Please enter a valid email address.";
}
if (empty($subject)) {
$errors['subject'] = "Please enter a subject.";
}
if (empty($message)) {
$errors['message'] = "Please enter your message.";
}
if (empty($errors)) {
// Prepare email
$to = "admin@example.com"; // Change to your admin email
$email_subject = "Contact Form: " . htmlspecialchars($subject);
$email_body = '
<html>
<head>
<style>
body { font-family: Arial, sans-serif; background: #f9f9f9; }
.email-container { background: #fff; padding: 24px; border-radius: 8px; box-shadow: 0 2px 8px #eee; }
.header { font-size: 17px; color: #333; margin-bottom: 16px; }
.info { margin-bottom: 12px; }
.label { font-weight: bold; color: #555; }
.message { background: #f1f1f1; padding: 12px; border-radius: 4px; }
</style>
</head>
<body>
<div class="email-container">
<div class="header">New Contact Form Submission</div>
<div class="info"><span class="label">Name:</span> ' . htmlspecialchars($name) . '</div>
<div class="info"><span class="label">Email:</span> ' . htmlspecialchars($email) . '</div>
<div class="info"><span class="label">Subject:</span> ' . htmlspecialchars($subject) . '</div>
<div class="label">Message:</div>
<div class="message">' . nl2br(htmlspecialchars($message)) . '</div>
</div>
</body>
</html>';
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: " . htmlspecialchars($name) . " <" . $email . ">\r\n";
$headers .= "Reply-To: " . $email . "\r\n";
// Send email
if (@mail($to, $email_subject, $email_body, $headers)) {
$success = "Thank you for contacting us! Your message has been sent.";
// Clear form fields after successful submission
$_POST = [];
} else {
$errors['general'] = "Sorry, there was a problem sending your message. Please try again later.";
}
}
}
?>
Note: Make sure to change the value of the $to variable to your admin email address where you want to receive the contact form submissions.
The code snippet mentioned above can be used as a ready-to-use script to add a contact form with email functionality to the website using PHP. We have used a professional UI in this contact form so that it fits with all types of webpage templates. But if you want, you can easily customize the functionality of this contact form to suit your needs. As an advanced feature, you can add captcha functionality to the contact form to protect against spam submissions – PHP Contact Form with Google reCAPTCHA.
Looking for expert assistance to implement or extend this script’s functionality? Submit a Service Request
💰 Budget-friendly • 🌍 Global clients • 🚀 Production-ready solutions
How to prevent reloading of the page after submission ?
Hi!
It works perfectly but I need to add a select with options to the form, would it affect anyhow? can you give me an example of what’ll change if I add it?
thanks!
Thank you for very informative tutorial you shared here. Please do I need to create database on hosting server before this code can run? Thanks
Very informative tutorial. I love it. Please I am a new PHP learner, before all this code should work do I need to create database with table on the hosting server ? Please I would appreciate your response as regards this.
Hi, how do i respond to the contact message afterwards. ? Thank you in advance.
Hello
Nice article thanks for all the
Hello thanks for the tutorial , But am geting this waning after testing the downloaded code.
Warning: 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 C:\xampp\htdocs\simple\index.php on line 40
How can i go about it sir?
PHP mail function will not work on localhost. You need to use SMTP server to send email from localhost. This tutorial may help you – https://www.codexworld.com/how-to-send-email-from-localhost-in-php/
one question how can i clean the echo message after sending the message? its always appearing after i sent a message i dont know how i clean after refreshing.
Define
$statusMsg = ''to prevent the status message after form submit.do you have tutorials that can use a yahoo mail? i mean users can also use a yahoo mail to send their message?
We have used “your_email@gmail.com” for example purpose, you can use Yahoo or any other email address.
I have my form set up at the bottom of my index page before the footer. I copied all of your code correctly. However…
When I click on the send button, the page simply jumps at the beginning of the index page. it seems like nothing happens. Could you guess why is that?
Make sure that you have placed the PHP form submission script at the beginning of the page.
do I need the phpmailer file? or just need to copy this code?
You don’t need phpmailer or any other file. Just use our script given in the tutorial.