Sending email, html > jQuery > PHP - javascript

I'm trying to send an email to myself with the text that has been entered in the textbox.
<form class="form align-center" id="mailchimp">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="newsletter-label font-alt">
Stay informed with our newsletter
</div>
<div class="mb-20">
<input placeholder="Enter Your Email" class="newsletter-field form-control input-md round mb-xs-10"
name="emaill" type="email" pattern=".{5,100}" required aria-required="true">
<button type="submit" aria-controls="subscribe-result" id="submit_btnn"
class="btn btn-mod btn-medium btn-round mb-xs-10">
Subscribe
</button>
</div>
<div class="form-tip">
<i class="fa fa-info-circle"></i> Please trust us, we will never send you spam
</div>
<div id="subscribe-result" role="region" aria-live="polite" aria-atomic="true"></div>
After that I catch it in Js
$(document).ready(function(){
$("#submit_btnn").click(function(){
//get input field values
var user_email = $('input[name=emaill]').val();
//simple validation at client's end
var proceed = true;
//we simply change border color to red if empty field using .css()
if (user_email == "") {
$('input[name=email]').css('border-color', '#e41919');
proceed = false;
}
//everything looks good! proceed...
if (proceed) {
//data to be sent to server
post_data = {
'userEmail': user_email
};
console.log(post_data);
//Ajax post data to server
$.post('nieuwsbrief.php', post_data, function(response){
//load json data from server and output message
if (response.type == 'error') {
output = '<div class="error">' + response.text + '</div>';
}
else {
output = '<div class="success">' + response.text + '</div>';
}
$("#subscribe-result").hide().html(output).slideDown();
}, 'json');
}
return false;
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function(){
$("#contact_form input, #contact_form textarea").css('border-color', '');
$("#subscribe-result").slideUp();
});
});
After that I want to use the Ajax post to send it to my php file
<?php
if($_POST)
{
echo '<script>console.log($_POST["userEmail"])</script>';
$to_Email = "mathias#wizewolf.com"; //Replace with recipient email address
$subject = 'Message from website '.$_SERVER['SERVER_NAME']; //Subject line for emails
echo '<script>console.log(to_Email)</script>';
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userEmail"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Message = "d";
$user_Message = str_replace("\'", "'", $user_Message);
$user_Message = str_replace("'", "'", $user_Message);
//additional php validation
if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($user_Message)<5) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
//proceed with PHP email.
$headers = 'From: '.$user_Email.'' . "\r\n" .
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$sentMail = #mail($to_Email, $subject, $user_Message . "\r\n\n" .'-- '.$user_Name. "\r\n" .'-- '.$user_Email, $headers);
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .'! Thank you for your email'));
die($output);
}
}
?>
With the console log, I've found out that until the start of the PHP file everything works. After that... not so much. All the tips and info are appreciated.

Instead of using jQuery and PHP, you could use STMP.js. I don't know how to answer this question with jQuery or PHP, but I know how to send emails with SMTP. I made an example on JSFiddle below. But, this might not work on JSFiddle for security reasons.
JSFiddle
https://jsfiddle.net/Yeet45687564/9prs4j2a/21/
// the javascript code below is also found on JSFiddle
let subject;
let body;
function setValues() {
// sets the values of the subject and body
subject = document.getElementById("emailSubject").value;
body = document.getElementById("emailBody").value;
}
function send() {
setValues();
// sends the email
Email.send({
Host: "smtp.gmail.com",
Username: "<sender's email address>",
Password: "<your email password>",
To: "<recipient's email address>",
From: "<sender’s email address>",
Subject: subject,
Body: body,
}).then(
// displays a message if the email was sent
message => alert("Your Email was sent.")
);
}
If you can't get this working, there is an SMTP tutorial on Pepipost.
https://pepipost.com/tutorials/how-to-send-emails-with-javascript/
But, using SMTP could be a huge security issue. Anyone who uses the inspect element on your website will be able to get your email password, unless you can block them from inspecting it and viewing the page source.

Related

Why does my contact form work in Brave but not other browsers?

My form works in Brave on my computer but does not work on Safari or Google on my computer. It also does not work on mobile devices. Where it does not work it returns a POST 409 Error.
Here is my html code.
<div class="row">
<div class="col-md-12 col-sm-12" id="result"></div>
<div class="col-md-3 col-sm-6">
<div class="form-group">
<label for="userName" class="d-none"></label>
<input class="form-control" type="text" placeholder="First Name:" required id="userName" name="userName">
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="form-group">
<label for="companyName" class="d-none"></label>
<input class="form-control" type="tel" placeholder="Company Name" id="companyName" name="companyName">
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="form-group">
<label for="email" class="d-none"></label>
<input class="form-control" type="email" placeholder="Email:" required id="email" name="email">
</div>
</div>
<div class="col-md-3 col-sm-6">
<button type="submit" class="button gradient-btn w-100" id="submit_btn">subscribe</button>
</div>
</div>
</form>
Here is my php code
<?php
use PHPMailer\PHPMailer\PHPMailer;
if($_POST)
{
require_once "PHPMailer/Exception.php";
require_once "PHPMailer/PHPMailer.php";
require_once "PHPMailer/SMTP.php";
$mail = new PHPMailer();
$your_email = "contact#thordigi.com"; //Replace with recipient email address
$to_Email = $your_email;
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Phone = $_POST["userPhone"];
//$user_Subject = $_POST["userSubject"];
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_Name)<3) // If length is less than 3 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($user_Message)<5) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
//Server settings
// $mail->isSMTP(); // Send using SMTP
// $mail->Host = 'smtp.googlemail.com'; // Set the SMTP server to send through
// $mail->SMTPAuth = true; // Enable SMTP authentication
// $mail->Username = 'website#gmail.com'; // SMTP username
// $mail->Password = 'your password'; // SMTP password
// $mail->SMTPSecure = 'TLS'; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
// $mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom($user_Email,$user_Name);
$mail->addAddress($your_email, 'Theme Industry'); // Add a recipient
$mail->addReplyTo($your_email, 'Information');
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'New Contact Inquiry from your Website';
$mail->Body = "<h4 style='text-align: center;padding: 25px 15px;background-color: #0c6c9e;color: #FFFFFF;font-size:16px;width:90%;border-radius: 10px;'>Hi There! You have a new inquiry from your website.</h4><br><br>";
$mail->Body .= "<strong>Name: </strong>". $user_Name ."<br>";
$mail->Body .= "<strong>Email: </strong>". $user_Email ."<br>";
$mail->Body .= "<strong>Phone: </strong>". $user_Phone ."<br>";
$mail->Body .= "<strong>Message: </strong>". $user_Message ."<br>";
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send())
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for contacting us.'));
die($output);
}
}
?>
Here is my Javascript code
//contact us
$("#submit_btn1 , #submit_btn").on('click', function () {
let userName = $('#name1').val();
let userEmail = $('#email1').val();
let userMessage = $('#message1').val();
let result;
if(this.id === 'submit_btn'){
result = $('#result');
userMessage = $('#companyName').val();
userName = $('#userName').val();
userEmail = $('#email').val();
}
else{
result = $('#result1');
}
//simple validation at client's end
let postData, output;
let proceed = true;
if (userName === "") {
proceed = false;
}
if (userEmail === "") {
proceed = false;
}
if (userMessage === "") {
proceed = false;
}
//everything looks good! proceed...
if (proceed) {
//data to be sent to server
postData = {
'userName': userName,
'userEmail': userEmail,
'userMessage': userMessage
};
//Ajax post data to server
$.post('https://thordigi.com/contact.php', postData, function (response) {
//load json data from server and output message
if (response.type === 'error') {
output = '<div class="alert-danger" style="padding:10px; margin-bottom:25px;">' + response.text + '</div>';
} else {
output = '<div class="alert-success" style="padding:10px; margin-bottom:25px;">' + response.text + '</div>';
//reset values in all input fields
$('.getin_form input').val('');
$('.getin_form textarea').val('');
}
result.slideUp("fast").html(output).slideDown();
}, 'json');
} else {
output = '<div class="alert-danger" style="padding:10px; margin-bottom:25px;">Please provide the missing fields.</div>';
result.slideUp("fast").html(output).slideDown();
}
});
I have been stuck on this for awhile so I really appreciate the help!
There are often broswer differences, and some are more forgiving than others. Errors like this are generally down to something not rendering correctly (so that your code can't find the right fields etc). To check the HTML, run it through the w3c validator and see what it suggests.
If that doesn't help, then to see exactly what is being sent and received by each browser, I'd recommend using a man-in-the-middle proxy (like burp) to intercept the request and response. From looking at the raw data, it is often quickly apparent what the problem is.

How to mail data from HTML form after it's checked by recaptcha?

I'm working on a contact website, where I want to have contact form. I want it to send data to e-mail and I want it to be checked by Google's recaptcha v3.
This is my second try. In the past, I've done it successfully without recaptcha. Now, I used this (https://codeforgeek.com/google-recaptcha-v3-tutorial/) tutorial, with following result:
script below the form
// when form is submit
$('#myform').submit(function() {
// we stoped it
event.preventDefault();
var mail = $('#email').val();
var comment = $("#sprava").val();
// needs for recaptacha ready
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('__SITE-KEY__', {action: 'create_comment'}).then(function(token) {
// add token to form
$('#myform').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
$.post("form.php",{mail: mail, comment: comment, token: token}, function(result) {
if(result.success) {
alert('Thanks for message')
} else {
alert('An error occured')
}
});
});;
});
});
</script>
the names of html form fields are "email", "vyber", "sprava"
form.php
<?php
$mail;$comment;$captcha;
$mail = filter_input(INPUT_POST, 'mail', FILTER_VALIDATE_EMAIL);
$comment = filter_input(INPUT_POST, 'comment', FILTER_SANITIZE_STRING);
$captcha = filter_input(INPUT_POST, 'token', FILTER_SANITIZE_STRING);
}
function email_sending(){
$webmaster_email = "bla#bla.com";
$sender_email= "blabla#bla.com" ;
$email_address = $_REQUEST['email'] ;
$selection = $_REQUEST['vyber'] ;
$message = $_REQUEST['sprava'];
$msg =
"E-mail: " . $email_address . "\r\n" .
"I'm interested in " . $selection . "\r\n" .
"Message: " . $message ;
mail( "$webmaster_email", "You have mail", $msg, $header);
}
if($responseKeys["success"]) {
echo json_encode(array('success' => 'true'));
email_sending();
} else {
echo json_encode(array('success' => 'false'));
}
?>
The problem isn't within recaptcha part, but then I recieve e-mail, where data is missing. (it shows only variable names, not actual values). I might think it's because of naming in script, as I'm not sure what to write in declaration of variables. I'd be glad to receive any input about this problem.
I managed to solve this problem by changing server-side code like below, thanks to this Recaptcha tutorial.
// 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 = '__SECRET-KEY___';
$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->success == true) {
// Verified - send email
} else {
// Not verified - show form error
}
}

How to integrate PHPMailer to this form to make it more secure?

I'd like to improve the contact form code (from a theme that I'm using) as it seems very basic and not secure at all (although I like in the current code the nice and smooth messages when a field is not filled in properly, or when the form is sent sucessfullly).
So, in order to make it more secure, I'd like to integrate PHPMailer to it.
Unfortunately, as I'm not very familiar with JS and PHP, I'm not sure where I should start? I'm assuming that I should somehow call PHPMailer just after //proceed with PHP email in the code below?
PHP:
<?php
if($_POST) {
$to_Email = "greg#dfsfsfsdfsfdsds.com"; //Replace with recipient email address
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=> 'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userSubject"]) || !isset($_POST["userMessage"])) {
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
//additional php validation
if(empty($_POST["userName"])) {
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) {
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($_POST["userMessage"])<5) {
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
//proceed with PHP email.
$headers = 'From: '.$_POST["userEmail"].'' . "\r\n" .
'Reply-To: '.$_POST["userEmail"].'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// send mail
$sentMail = #mail($to_Email, $_POST["userSubject"], $_POST["userMessage"] .' -'.$_POST["userName"], $headers);
if(!$sentMail) {
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
} else {
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$_POST["userName"] .' Thank you for your email'));
die($output);
}
}
?>
JS:
/*******************
* Contact Form JavaScript
********************/
$(document).on("ready",function() {
$("#email-form [type='submit']").click(function(event) {
event.preventDefault();
//get input field values
var user_name = $('input[name=name]').val()
var user_email = $('input[name=email]').val()
var user_subject = $('input[name=subject]').val()
var user_message = $('textarea[name=message]').val()
//data to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userSubject':user_subject, 'userMessage':user_message}
//Ajax post data to server
$.post('contact_me.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error') {
output = '<div class="error-message"><p class="from">'+response.text+'</p></div>'
} else {
output = '<div class="success-message"><p class="seuccses">'+response.text+'</p></div>'
//reset values in all input fields
$('#email-form input').val('')
$('#email-form textarea').val('')
}
$("#result").hide().html(output).slideDown()
}, 'json')
});
//reset previously set border colors and hide all message on .keyup()
$("#email-form input, #email-form textarea").keyup(function() {
$("#result").slideUp()
})
});

Javascript not getting called on form submit

I have a pretty simple form in html from which i am trying to send an email. I checked online for some tutorials sing js but most of them were not working. Here is my code the form is there but when i press submit the js function is not getting called rather it is not doing anything on the html form.
<form class="form-inline" id="contact-form" onSubmit="return false">
<center><p><input style="height:3vw;width:40vw;font-size:1.2vw;" type="text" class="form-control" size="30" placeholder=" Name" name="name" id="name" required></p>
<p><input style="height:3vw;width:40vw;font-size:1.2vw;" type="email" class="form-control" size="30" placeholder=" E-mail Address" name="email" id="email" required></p>
<p><input style="height:3vw;width:40vw;font-size:1.2vw;" type="text" class="form-control" size="30" placeholder=" Subject" name="subject" id="subject" required></p>
<p><textarea style="height:10vw;width:40vw;font-size:1.2vw;" placeholder=" Message..." class="form-control" name="message" id="message"></textarea></p>
<p><button type="submit" class="button" name="btn_submit" id="btn_submit">Send</button></p></center>
</form>
i have included the js file as it is after the <div> ending of the form
<script src="js/jquery-2.1.4.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/functions.js"></script>
functions.js file is as follows
//Contact Us
$("#btn_submit").click(function() {
//get input field values
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_message = $('textarea[name=message]').val();
//simple validation at client's end
var proceed = true;
if(user_name==""){
proceed = false;
}
if(user_email==""){
proceed = false;
}
if(user_message=="") {
proceed = false;
}
//everything looks good! proceed...
if(proceed)
{
//data to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userMessage':user_message};
//Ajax post data to server
$.post('contact_me.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="alert-danger">'+response.text+'</div>';
}else{
output = '<div class="alert-success">'+response.text+'</div>';
//reset values in all input fields
$('.form-inline input').val('');
$('.form-inline textarea').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
and my email handler is as follows :
<?php
if($_POST)
{
$to_Email = "email.com"; //Replace with recipient email address
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userSubject"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Subject = filter_var($_POST["userSubject"], FILTER_SANITIZE_STRING);
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_Name)<3) // If length is less than 3 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($user_Message)<5) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
$subject = $user_Subject;
$message_Body = "<strong>Name: </strong>". $user_Name ."<br>";
$message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
$message_Body .= "<strong>Message: </strong>". $user_Message ."<br>";
$headers = "From: " . strip_tags($user_Email) . "\r\n";
$headers .= "Reply-To: ". strip_tags($user_Email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
//proceed with PHP email.
/*$headers = 'From: '.$user_Email.'' . "\r\n" .
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
*/
$sentMail = #mail($to_Email, $subject, $message_Body, $headers);
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for contacting us.'));
die($output);
}
}
?>
On pressing submit the js file is not being called and there is no error in console either. Can anyone please help me out where i am making the mistake. Thank you.
You need to prevent the default form submission action which is to refresh the page.
You need to add a parameter to your function that can track the event and then call preventDefault() from that parameter:
$("#btn_submit").click(function(e) {
e.preventDefault();
...
}
Try replacing
$("#btn_submit").click(function() {
with
$(document).on("click,", "#btn_submit", function(){
You need to prevent the form from submitting, otherwise it will just directly submit and turn to the server-side.
You can do such a thing using jQuery:
$("#btn_submit").click(function(e) {
e.preventDefault();
//your code goes here after preventing submission
}

How to correctly connect reCAPTCHA?

Got contact form like this (JSFiddle).
Registered captcha. How to implement the correct integration on the client and server?
In the form inserted just a div. Submit gonna work like this? How to connect submit and captcha?
It refers to the POST request:
How does it send?
There is PHP:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$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"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
$recipient = "mail#mail.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
I have integrated the google reCaptcha in our website. Here is our implementation.
Front-end Code:
<script src="https://www.google.com/recaptcha/api.js?onload=recaptchaCallBack&render=explicit" async defer></script>
<script type="text/javascript">
var recaptcha_sponsorship_signup_form;
var recaptchaCallBack = function() {
// Render the recaptcha on the element with ID "recaptcha_sponsorship_signup_form"
recaptcha_sponsorship_signup_form = grecaptcha.render('recaptcha_sponsorship_signup_form', {
'sitekey' : 'your_recaptcha_website_key',
'theme' : 'light'
});
};
</script>
<dt>Prove you’re not a robot</dt>
<dd style="height: 78px;">
<div id="recaptcha_sponsorship_signup_form"></div>
</dd>
Server Side Code:
$fileContent = '';
if (isset($_REQUEST['g-recaptcha-response']) && !empty($_REQUEST['g-recaptcha-response'])) {
$fileContent = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=your_recaptcha_secret_key&response=". $_REQUEST['g-recaptcha-response']);
}
$jsonArray = json_decode($fileContent, true);
if (isset($jsonArray['success']) && $jsonArray['success']==true) {
// process your logic here
} else {
echo "Invalid verification code, please try again!";
}
You can use this library ;
https://github.com/google/recaptcha/blob/master/examples/example-captcha.php
First, register keys for your site at https://www.google.com/recaptcha/admin
When your app receives a form submission containing the g-recaptcha-response field, you can verify it using:
<?php
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);
if ($resp->isSuccess()) {
// verified!
} else {
$errors = $resp->getErrorCodes();
}
You can see an end-to-end working example in examples/example-captcha.php

Categories