Unable to implement reCaptcha in HTML Form - php

I am new to Web development and I am trying to implement reCaption in my HTML form.
I tried many online tutorials but I was unable to implement it propoerly in my code.
Head :
<script src="https://www.google.com/recaptcha/api.js?render=6LfRQZ4UAAAAAAuMMBQhrBVmyjkVsD"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('6LfRQZ4UAAAAAAuMMBhzvMWVmyjkVsD', { action: 'contact' }).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
});
});
</script>
Form :
<form id="ajax-contact" method="post" action="mailer.php">
<fieldset>
<div class="form-field">
<input type="text" id="name" name="name" placeholder="Full Name" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input type="email" id="email" name="email" placeholder="Email" value="" required="" aria-required="true" class="full-width"placeholder="Telephone Number" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="telno" type="text" id="telno" placeholder="Telephone Number" value="" required="" aria-required="true" class="full-width">
</div>
<div class="form-field">
<input name="subj" type="text" id="subj" placeholder="Subject" value="" class="full-width">
</div>
<div class="form-field">
<textarea id="message" name="message" placeholder="Leave Message" value="" required="" aria-required="true" class="full-width"></textarea>
</div>
<div class="form-field">
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
</div>
<div class="form-field">
<button id="submit" type="submit" name="submit" class="full-width btn--primary">SEND</button>
<div class="submit-loader">
<div class="text-loader">Sending...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
mailer.php :
<?php // Check if form was submitted:
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['recaptcha_response'])) {
// Build POST request:
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = '6LfRQZ4UAAAAAJhdTvqgZyMJB-HO4XL_';
$recaptcha_response = $_POST['recaptcha_response'];
// Make and decode POST request:
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
// Take action based on the score returned:
if ($recaptcha->score >= 0.5) {
// Verified - send email
} else {
// Not verified - show form error
}
} ?>
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
$telno = trim($_POST["telno"]);
$subj = trim($_POST["subj"]);
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
$recipient = "user#mail.com";
$subject = "New contact from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n";
$email_content .= "Telephone Number: $telno\n";
$email_content .= "Subject : $subj\n\n";
$email_content .= "Message:\n$message\n";
$email_headers = "From: $name <$email>";
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
app.js :
$(function() {
var form = $('#ajax-contact');
var formMessages = $('#form-field');
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response);
$('#name, #email, #telno, #subj, #message').val('');
})
.fail(function(data) {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
I want add reCatcha in this form to avoid spammers.
I tried official google docs also but I was unable to implement that properly in my code.
Thanks in advance for any solution.

Related

Ajax form validation in php

Im trying to create ajax from with php validation, let explain with screenshot. while validating form im getting all error in same placeā€¦
what im trying to get is individual validation for field like below
And after form is submitted i want display success message at the top of form but im getting success message on all field
html form data (index.php)
<form id="first_form" method="POST" action="form.php">
<p class="form-message"></p>
<div class="mb-3">
<input type="text" class="form-control" id="name" name="name" placeholder="Name:">
<p class="form-message"></p>
</div>
<div class="mb-3">
<input type="tex" class="form-control" id="email" name="email" placeholder="Email:">
<p class="form-message"></p>
</div>
<div class="mb-3">
<input type="text" class="form-control" id="phone" name="phone" placeholder="Phone:">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="address" name="address" placeholder="Address:">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject:">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="services" name="services" placeholder="Services:">
</div>
<div class="mb-3">
<textarea class="form-control" rows="5" id="message" name="message" placeholder="Leave Your Message..."></textarea>
</div>
<button type="submit" name="submit" id="submit" class="btn btn-primary">Submit</button>
js code:
$(document).ready(function() {
$("#first_form").submit(function(event) {
event.preventDefault();
name = $("#name").val();
email = $("#email").val();
phone = $("#phone").val();
address = $("#address").val();
subject = $("#subject").val();
services = $("#services").val();
message = $("#message").val();
submit = $("#submit").val();
$(".form-message").load("form.php", {
name: name,
email: email,
phone: phone,
address: address,
subject: subject,
services: services,
message: message,
submit: 'submitted'
});
});
});
form.php data
if (isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = "Contact Form";
$mailTo = "hello#develoweb.com";
$headers = "From: ".$email;
$txt = "You have received a message from ".$name.
".\n\n".$message;
$errorEmptyname = false;
$errorEmptyemail = false;
$errorEmptymessage = false;
$errorEmail = false;
if (empty($name)) {
echo "<span class='form-error'>Name Field cannot be empty</span> ";
//$errorEmptyName = true;
}
if (empty($email)) {
echo "<span class='form-error'>Email Field cannot be empty</span>";
//$errorEmptyemail = true;
}
if (empty($message)) {
//$errorEmptymessage = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>
Write a valid e-mail addres </span>";
$errorEmail = true;
}
else {
echo "<span class='form-success'>
Thank you for your message!<br>
I'll get back to you as soon as I can.</span>";
mail($mailTo, $subject, $body, $headers);
}
}
else{
echo "There was an error!";
}
what i have understand, im not getting individual validation error in individual field bcz class is same, how can i append error to related fields
i havent used js validation bcz i want to some validation for spammer to prevent spam mail and as we know while viewing source code we can easily view code for validation too, so pefer validation in php

Contact Form Not Found Error after submitting

after sending message on contact form, results shows 404 error instead of success message. I have tried many times, i don't know what is missing. Any help will be very appreciated.
Second issue is also there, it shows:
Uncaught TypeError: $ is not a function
at contact.js?ver=20170915:1
here is the html code
<!-- Start Contact Form -->
<div class="col-lg-4 col-md-5 col-xs-12">
<div class="alert alert-info text-center " role="alert">
<h5>Contact</h5>
</div>
<form id="contact-form" method="post" action="contact.php" role="form">
<form role="form" id="contactForm" class="contact-form" data-toggle="validator">
<div class="form-group">
<div class="controls">
<input type="text" name="name" id="name" class="form-control" placeholder="Name" required data-error="Please enter your name">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="email" name="email" class="email form-control" id="email" placeholder="Email" required data-error="Please enter your email">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="text" name="msg_subject" id="msg_subject" class="form-control" placeholder="Subject" required data-error="Please enter your message subject">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<textarea id="message" rows="3" name="message"placeholder="Massage" class="form-control" required data-error="Write your message"></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<button type="submit" id="submit" class="btn btn-block bg-info">Send Message</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
</div>
</div>
</div>
<!-- Contact Form Section End -->
And i have added contact.php page
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// MSG SUBJECT
if (empty($_POST["msg_subject"])) {
$errorMSG .= "Subject is required ";
} else {
$msg_subject = $_POST["msg_subject"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
//Add your email here
$EmailTo = "chandanicfai1#gmail.com";
$Subject = "New Message Received";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Subject: ";
$Body .= $msg_subject;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
contact.js file is
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Did you fill in the form properly?");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var msg_subject = $("#msg_subject").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "contact.php",
data: "name=" + name + "&email=" + email + "&msg_subject=" + msg_subject + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "Message Submitted!")
}
function formError(){
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
}
function submitMSG(valid, msg){
if(valid){
var msgClasses = "h3 text-center tada animated text-success";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
and also form validator
https://github.com/1000hz/bootstrap-validator/blob/master/js/validator.js

form submission error html & php

I am buidling a php contact form with ajax validation. While I submit the contact form I get error message "spammer" which is not supposed to.
Below is my code html & php code.
Index.php
<form id="contactform" method="post" action="mailer.php">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="username" placeholder="Enter your name">
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="text" class="form-control" id="phone" name="phone" placeholder="Enter your phone number">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter your email address">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" id="message" name="message" rows="4" placeholder="Enter your email message"></textarea>
</div>
<br>
<div class="g-recaptcha" data-sitekey="6Lct9zUUAAAAABpj9vwKX9B7x_AH8s9gwJzFW1sB"></div>
<br>
<div id="formresult">
</div>
<button type="submit" name="submit" class="btn btn-info">Submit</button>
</form>
Mailer.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["username"]);
$phone = trim($_POST["phone"]);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
if(isset($_POST['g-recaptcha-response'])){
$captcha = $_POST['g-recaptcha-response'];
}
//Validate the data
if (empty($name) OR empty($phone) OR !filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($message) OR empty($captcha)) {
http_response_code(400);
echo "<span class='glyphicon glyphicon-remove' aria-hidden='true'></span> <strong>Please fill all the form inputs and check the captcha to submit.</strong>";
exit;
}
//recipient email address.
$recipient = "abc#abc.com";
$subject = "New message from $name";
//email content.
$email_content = "Name: $name\n";
$email_content .= "Phone: $phone\n\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
//email headers
$email_headers = "From: $name <$email>";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR_SECRATE_KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
$decoded_response = json_decode($response, true);
if($decoded_response['success'] == true){
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo "<span class='glyphicon glyphicon-ok' aria-hidden='true'></span> <strong>Thank You! Your message has been sent.</strong>";
} else {
http_response_code(500);
echo "Your message cannot be sent";
}
} else {
http_response_code(400);
echo 'spammer!';
}
}
?>
When I submit the form I get a error message 'spammer' and even mail does not get through.
I know there is some mistake in logic but i cannot figure it out.
Anyone please help me in this. Thank you.
The line of code:
if($decoded_response['success'] == true){
Must be evaluating to false, and executing the else part of that statement. Displaying the spammer message.
Check the decoded contents returned from the recaptcha url, that you assign to the $decoded_response variable.
print_r($decoded_response); // should show the whole contents

Contact form won't submit data

I have a JSON code in a sendemail.php file for my Bootstrap 3 contact form. The form is able to send an email to the specified email address but there is no data being submitted. I get blank emails with labels and the header 'unknown sender'. Please help solve this.
This is the bootsrap form code chunk
<div class="col-sm-6">
<h1>Contact Form</h1>
<p>Please contact us using the form or our contact details are available here if you'd like to contact us via Email or Phone.</p>
<div class="status alert alert-success" style="display: none"></div>
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php" role="form">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<input type="text" name="Name" class="form-control" required placeholder="Name">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="text" name="Email" class="form-control" required placeholder="Email address">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<textarea name="Message" id="message" required class="form-control" rows="8" placeholder="Message"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger btn-lg">Send Message</button>
</div>
</div>
</div>
</form>
</div><!--/.col-sm-6-->
This is the main.js code where the AJAX for contact form is present
jQuery(function($) {
$(function(){
$('#main-slider.carousel').carousel({
interval: 5000,
pause: false
});
});
//Ajax contact
var form = $('.contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
//smooth scroll
$('.navbar-nav > li').click(function(event) {
if(!$( this ).attr( 'href' ).match(/^#/)) return;
event.preventDefault();
var target = $(this).find('>a').prop('hash');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 500);
});
//scrollspy
$('[data-spy="scroll"]').each(function () {
var $spy = $(this).scrollspy('refresh')
})
//PrettyPhoto
$("a.preview").prettyPhoto({
social_tools: false
});
//Isotope
$(window).load(function(){
$portfolio = $('.portfolio-items');
$portfolio.isotope({
itemSelector : 'li',
layoutMode : 'fitRows'
});
$portfolio_selectors = $('.portfolio-filter >li>a');
$portfolio_selectors.on('click', function(){
$portfolio_selectors.removeClass('active');
$(this).addClass('active');
var selector = $(this).attr('data-filter');
$portfolio.isotope({ filter: selector });
return false;
});
});
});
This is the sendemail.php code
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent!'
);
$name = $_POST['Name'];
$email = $_POST['Email'];
$subject = $_POST['Subject'];
$message = $_POST['Message'];
$email_from = $email;
$email_to = 'myemail#domain.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
?>
You are missing the name attribute in your html input tags
This is required for the server side variables, for example:
$name = $_POST['Name'];
will get value from
<input type="text" name="Name" class="form-control" required placeholder="Name">
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php" role="form">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<input name="Name" type="text" class="form-control" required placeholder="Name">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input name="Email" type="text" class="form-control" required placeholder="Email address">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<textarea name="Message" id="message" required class="form-control" rows="8" placeholder="Message"></textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-danger btn-lg" value="Send Message">
</div>
</div>
</div>
</form>
<?php
if(isset($_POST['submit'],$_POST['Name'],$_POST['Email'],$_POST['Subject'],$_POST['Message'])){
$name = $_POST['Name'];
$email = $_POST['Email'];
$subject = $_POST['Subject'];
$message = $_POST['Message'];
$email_from = $email;
$email_to = 'myemail#domain.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
$response = array();
if($success){
$response['success'] = true;
$response['message'] = 'Email sent!';
}else{
$response['success'] = false;
$response['message'] = 'Email sent!';
}
}else{
$response['success'] = false;
$response['message'] = 'post variables are not set';
}
echo json_encode($response);
//die;
Change this line in main.js:
$.post($(this).attr('action'), function(data) {
to:
$.post($(this).attr('action'), $(this).serialize(), function(data) {
It will now submit the data.

Why won't my contact form email me after submission?

I am very new to PHP, so please bear with me here.
It seems like the form goes through, I don't get any errors, but I never receive an email.
Thank you in advance!!
Here is my html
<form class="form-horizontal" role="form" method="POST" id="contact-form" action="contact-form/form.php" style="padding-bottom: 5em;">
<div class="form-group">
<label class="sr-only" for="name">Name</label>
<div class="col-md-12">
<input type="text" class="form-control" name="name" id="name" placeholder="Enter Name">
</div>
</div>
<br>
<div class="form-group">
<label class="sr-only" for="email">Email</label>
<div class="col-md-12">
<input type="email" class="form-control" name="email" id="email" placeholder="Enter Email">
</div>
</div>
<br>
<div class="form-group">
<label class="sr-only" for="message">Message</label>
<div class="col-md-12">
<textarea class="form-control" name="message" rows="10"></textarea>
</div>
</div>
<br>
<div class="form-actions">
<input type="hidden" name="save" value="contact">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
Here is my php
<?php
// check for form submission - if it doesn't exist then send back to contact form
if (!isset($_POST["save"]) || $_POST["save"] != "contact") {
header("Location: ../index.php"); exit;
}
// get the posted data
$name = $_POST["name"];
$email_address = $_POST["email"];
$message = $_POST["message"];
$headers = 'From: '.$email_address."\r\n" .
'X-Mailer: PHP/' . phpversion();
// write the email content
$email_content = "Name: $name\n";
$email_content .= "Email Address: $email_address\n";
$email_content .= "Message:\n\n$message";
// send the email
mail ("myEmail", "Someone Wants a Website!", $email_content, $headers);
$to = $_POST['email'];
$subject = 'Thank you for contacting me!';
$msg = 'I have recieved your correspondence and will get back to you as soon as I can. Best regards, Mike Wilcox Designs';
mail($to, $subject, $msg);
header("Location: ../index.php"); exit;
?>
I am also using jquery validate
<script>
$(document).ready(function () {
$('#contact-form').validate({
rules: {
name: {
minlength: 2,
required: true
},
email: {
required: true,
email: true
},
message: {
minlength: 2,
required: true
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function (element) {
element.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
});
</script>

Categories