Easy PHP Contact form including Mobile with Ajax Validation and captcha CSS included
Easy, PHP Contact form, including Mobile, Ajax Validation. captcha, CSS included
This is easy, simple copy paste PHP contact form for with full Ajax and captcha validation
Save the Below code in a simple index.php and save it
<?php
// Variables
$name = "";
$email = "";
$mobile = "";
$message = "";
$errorMessage = "";
$captchaError = "";
// CAPTCHA configuration
$captchaSecret = "YOUR_CAPTCHA_SECRET_KEY";
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Retrieve form data
$name = sanitizeInput($_POST["name"]);
$email = sanitizeInput($_POST["email"]);
$mobile = sanitizeInput($_POST["mobile"]);
$message = sanitizeInput($_POST["message"]);
$captchaResponse = $_POST["g-recaptcha-response"];
// Validate CAPTCHA
$captchaUrl = "https://www.google.com/recaptcha/api/siteverify";
$captchaData = [
"secret" => $captchaSecret,
"response" => $captchaResponse,
"remoteip" => $_SERVER["REMOTE_ADDR"]
];
$ch = curl_init($captchaUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($captchaData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$captchaResult = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$captchaResult["success"]) {
$captchaError = "CAPTCHA verification failed. Please try again.";
}
// Validate form data
if (empty($name) || empty($email) || empty($mobile) || empty($message)) {
$errorMessage = "All fields are required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errorMessage = "Invalid email format.";
} elseif (!preg_match("/^[0-9]{10}$/", $mobile)) {
$errorMessage = "Invalid mobile number format.";
}
// If no errors, send the email
if (empty($errorMessage) && empty($captchaError)) {
$to = "[email protected]";
$subject = "New Contact Form Submission";
$emailBody = "Name: $name\nEmail: $email\nMobile: $mobile\nMessage: $message";
$headers = "From: $email";
if (mail($to, $subject, $emailBody, $headers)) {
// Email sent successfully
echo "success";
exit;
} else {
$errorMessage = "Failed to send the email. Please try again later.";
}
} else {
// Return error message for AJAX validation
echo $errorMessage;
exit;
}
}
// Helper function to sanitize form input
function sanitizeInput($input)
{
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Contact Form</title>
<style>
.contact-form {
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
.contact-form label {
display: block;
margin-bottom: 10px;
}
.contact-form input[type="text"],
.contact-form input[type="email"],
.contact-form input[type="tel"],
.contact-form textarea {
width: 100%;
padding: 10px;
border-radius: 3px;
border: 1px solid #ccc;
margin-bottom: 15px;
}
.contact-form button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 3px;
cursor: pointer;
}
.contact-form .error {
color: red;
margin-top: 5px;
}
</style>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$(".contact-form").on("submit", function (e) {
e.preventDefault();
var form = $(this);
var url = form.attr("action");
var formData = form.serialize();
$(".error").html(""); // Clear previous error messages
$.ajax({
type: "POST",
url: url,
data: formData,
success: function (response) {
if (response === "success") {
// Display success message
form.html("<p>Thank you for your message!</p>");
} else {
// Display error message(s)
$(".error").html(response);
}
}
});
});
});
</script>
</head>
<body>
<div class="contact-form">
<h1>Contact Form</h1>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<?php echo $name; ?>">
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="<?php echo $email; ?>">
</div>
<div>
<label for="mobile">Mobile:</label>
<input type="tel" id="mobile" name="mobile" value="<?php echo $mobile; ?>">
</div>
<div>
<label for="message">Message:</label>
<textarea id="message" name="message"><?php echo $message; ?></textarea>
</div>
<div class="g-recaptcha" data-sitekey="YOUR_CAPTCHA_SITE_KEY"></div>
<?php if (!empty($captchaError)) : ?>
<p class="error"><?php echo $captchaError; ?></p>
<?php endif; ?>
<div>
<button type="submit">Submit</button>
</div>
<?php if (!empty($errorMessage)) : ?>
<p class="error"><?php echo $errorMessage; ?></p>
<?php endif; ?>
</form>
</div>
</body>
</html>
Donot forget to replace "YOUR_CAPTCHA_SECRET_KEY"
with your actual reCAPTCHA secret key and "YOUR_CAPTCHA_SITE_KEY"
with your actual reCAPTCHA site key.
Next,
replace "[email protected]"
to your email address where you want to receive the contact form mails.
Included CSS styles for the form
You can customize the CSS according to your preference
More on PHP