Ajax and PHP form - 500 (Internal Server Error) - javascript

I have a contact form that will be sent to an e-mail, but when I try to send I get the 500 Internal Server Error.
I already check probable errors like wrong variable name on HTML file and these stuff.
My hosting is Digital Ocean.
Here is my js code:
var form = $('#form-contact');
var formMessages = $('#form-messages');
$(form).submit( function( event ) {
event.preventDefault();
var formData = $(form).serialize();
$.ajax({
type : 'POST',
url : $(form).attr('action'),
data : formData,
beforeSend: function(){
$(".load").show();
},
})
.done( function( response ) {
$(".load").hide();
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response);
$('#form-contact input').val('');
$('#form-contact textarea').val('');
})
.fail( function( data ) {
$(".load").hide();
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Sending
if ( data.response !== '' ) {
$(formMessages).text( data.responseText );
} else {
$(formMessages).text( 'error.' );
}
});
} );
And here, my PHP code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["user_name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["user_email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["user_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 "error.";
exit;
}
// Set the recipient email address.
$recipient = "mail#here.com";
// Set the email subject.
$subject = "New contact from " . $name;
// Build the email content.
$email_content = "Name: ". $name;
$email_content .= "\nE-mail: ". $email;
$email_content .= "\n\nMessage:\n " . $message;
// 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 "Thanks, your message was sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "OOps! Sorry, error.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "Problem with your request!";
}

That 500 is coming from your own code: http_response_code(500);
The reason your getting it is because mail() is returning false, which means that it's not configured properly. You'll need to install and set up postfix or fakesendmail.

Related

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()
})
});

How do you execute actions after the form is successfully processed?

I want to make the form hide and a thank you message appear instead of it after the form is successfully submitted. I've done the below code but I cannot manage to get any action performed after the form is submitted .. it's like the 'if' function is ignored.
Below is my code:
JQuery:
$('form#contactform').submit(function(event) {
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val(),
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
//Done promise callback
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (! data.success == true) {
$('section#contact form#contactform').hide;
$('section#contact div.thxform').show;
} else {
alert("An internal error has occured");
}
});
//Stop form default action
event.preventDefault();
Php:
<?php
$errors = array(); //array to hold validation errors
$data = array(); //array to pass back data
//validate variables
if (empty($_POST['name']))
$errors['name'] = 'Name is required';
if (empty($_POST['email']))
$errors['email'] = 'E-Mail is required';
if (empty($_POST['subject']))
$errors['subject'] = 'Subject is required';
if (empty($_POST['message']))
$errors['message'] = 'Please enter a message';
//Return response
if ( ! empty($errors)) { //If there are errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
//Process form
$name = $_POST['name'];
$email = $_POST['email'];
$re = $_POST['subject'];
$message = $_POST['message'];
$from = 'info#jamescremona.com';
$to = 'jmscre#gmail.com';
$subject = 'Form submission';
$body = "From: $name\n E-mail: $email\n Subject: $re\n Message: $message\n";
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
$data['success'] = true;
$data['message'] = 'Form Submitted';
}
echo json_encode($data);
Any help would be greatly appreciated. Thanks.
First error I spotted on your code :
'message' : $("#msg").val(), that is your last item in your array therefore no need for the ',' javascript expect more items after','
You need to check all you js errors in the console, they are there.
then the second error I saw,
$('section#contact form#contactform').hide;
$('section#contact div.thxform').show;
show and hide does not exist in jquery they have show(); and hide(); then here : if (! data.success == true) {}
This is how your code should look :
<script type="text/javascript">
$('form#contactform').submit(function(event) {
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val()
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (!data.success) {
$('section#contact form#contactform').hide();
$('section#contact div.thxform').show();
//check which field was wrong and show the user
if(data.errors.name){
$('section#contact div.thxform').append(data.errors.name);
}
if(data.errors.email){
$('section#contact div.thxform').append(data.errors.email);
}
if(data.errors.subject){
$('section#contact div.thxform').append(data.errors.subject);
}
if(data.errors.message){
$('section#contact div.thxform').append(data.errors.message);
}
}else{
$('#successDIV').append(data.message);
}
}),
.fail(function(data){
//debugging puporses, all your php errors will be printed in the console
console.log(data);
});
//Stop form default action
event.preventDefault();
</script>
You need to tell the browser what to expect. So add the header function before your echo
header('Content-Type: application/json'); // this line here
echo json_encode($data);
UPDATE
Also your event.preventDefault(); comes last which should be the first thing you call after $('form#contactform').submit(function(event) { since you want to prevent stuff before the ajax call.
Also you PHP is echoing stuff in either case of the mail functions return value. So the json response is messed up, thus your ajax will not get proper data back.
UPDATE 2
I have the strong feeling that your PHP script is throwing errors of some sort. The mail function could be throwing a 530 error for example. So best you disable error displaying in your PHP script.
General advice for debugging this sort of stuff is web developer browser extensions to view request/response information.
Try this refactored code please:
ini_set('display_errors',0); // disable error displaying. Rather view in logs
$errors = array(); //array to hold validation errors
$data = array(); //array to pass back data
//validate variables
if (empty($_POST['name']))
$errors['name'] = 'Name is required';
if (empty($_POST['email']))
$errors['email'] = 'E-Mail is required';
if (empty($_POST['subject']))
$errors['subject'] = 'Subject is required';
if (empty($_POST['message']))
$errors['message'] = 'Please enter a message';
//Return response
if ( ! empty($errors)) { //If there are errors
$data['errors'] = $errors; // only necessary to set errors
} else {
//Process form
$name = $_POST['name'];
$email = $_POST['email'];
$re = $_POST['subject'];
$message = $_POST['message'];
$from = 'info#jamescremona.com';
$to = 'jmscre#gmail.com';
$subject = 'Form submission';
$body = "From: $name\n E-mail: $email\n Subject: $re\n Message: $message\n";
if (mail ($to, $subject, $body, $from)) {
$data['success'] = 'Your message has been sent!'; // store to $data instead of echo out
} else {
$data['errors'] = 'Something went wrong, go back and try again!'; // store to $data instead of echo out
}
}
header('Content-Type: application/json');
echo json_encode($data);
And your javascript snippet in the done function of the ajax call:
<script type="text/javascript">
$('#contactform').submit(function(event) {
event.preventDefault(); // note this one has to be at the beginning of your submit function since you do not want to submit
var formData = {
//get form data
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'subject' : $('input[name=subject]').val(),
'message' : $("#msg").val(),
};
$.ajax({
type : 'POST',
url : 'sendmail.php',
data : formData,
dataType : 'json',
encode : true
})
//Done promise callback
.done(function(data) {
//log data to console
console.log(data);
//Errors and validation messages
if (data.success) { // success either exists or not
alert("Success! Form should hide now...");
$('#contactform').hide(); // an id is (should always) be unique. So you dont need this "section#contact form#contactform". It does not make sense. Also hide and show are functions and need brackets at the end
$('div.thxform').show();
} else { // then its an error
alert("An internal error has occured");
}
});
});
</script>
And the HTML i used to test this:
<form method="post" id="contactform">
Name <input type="text" name="name" value="test"><br>
Email <input type="text" name="email" value="test#localhost.com" ><br>
Subject <input type="text" name="subject" value="subject" ><br>
Message <textarea name="message" ></textarea><br>
<input type="submit">
</form>
Its because of 2 tiny mistakes:
[js code] Replace if (! data.success == true) with if (data.success == true).
[php code] add header('Content-Type: application/json'); before echoing $data
I guess the problem is here
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
because you echo a string and then a json object. Therefore when you treat data response on Javascript, it's not a json object.
Then I would do as follow in PHP
if (#mail($to, $subject, $body, $from)) {
$data['success'] = true;
$data['message'] = 'Form Submitted';
} else {
$data['success'] = false;
$data['message'] = 'Internal error';
}
echo json_encode($data);
and in Javascript
.done(function(data) {
if (typeof data !== 'object') {
alert('Expected data as object - '+typeof data+' received');
return;
}
data = jQuery.parseJSON(data);
//Errors and validation messages
if (data.success == true) {
$('section#contact form#contactform').hide;
$('section#contact div.thxform').show;
} else {
alert(data.message);
}
});
Note that the # operator before mail function will not generate error messages to avoid sending a string on Javascript.

ajax, jquery contact form with reCAPTCHA v2 - 500 Internal Server Error

I have a jquery/ajax contact form and tried to add the Google reCAPTCHA v2, but it isn't working. The form worked before I included the reCAPTCHA. The reCAPTCHA shows up (although it takes forever to load), and I can verify that I'm not a robot (which takes forever as well), but when I click on my submit button, the spot where I display my status messages shows this, including the code, as text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>500 Internal Server Error</title> </head><body> <h1>Internal Server Error</h1> <p>The server encountered an internal error or misconfiguration and was unable to complete your request.</p> <p>Please contact the server administrator, and inform them of the time the error occurred, and anything you might have done that may have caused the error.</p> <p>More information about this error may be available in the server error log.</p> </body></html>
I can't figure out what's going wrong. I followed Google's instructions and included this just before my tag:
<script src='https://www.google.com/recaptcha/api.js'></script>
and integrated my form like this:
<div class="g-recaptcha" data-sitekey="6LeehAsUAAAAAILDfzizJ23GHH7yPGxWBFP_3tE7"></div>
I tried many different ways to integrate it in my mailer.php file without success, and I couldn't find many tutorials that address v2 specifically (not sure if it even matters). My most recent version of the mailer.php is based on an example I found on Google's recaptcha Github:
<?php
require_once __DIR__ . 'inc/autoload.php';
// If the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// If the Google Recaptcha box was clicked
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
$siteKey = '6LeehAsUAAAAAILDfzizJ23GHH7yPGxWBFP_3tE7';
$secret = 'I-removed-this-for-now';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);
// If the Google Recaptcha check was successful
if ($resp->isSuccess()){
$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"]);
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 = "I-removed-this#for-now.com";
$subject = "New message from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\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. Check your email address.";
}
}
// If the Google Recaptcha check was not successful
else {
echo "Robot verification failed. Please try again.";
}
}
// If the Google Recaptcha box was not clicked
else {
echo "Please click the reCAPTCHA box.";
}
}
// If the form was not submitted
// Not a POST request, set a 403 (forbidden) response code.
else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
This is the app.js that goes with my contact form (I haven't changed this at all when trying to include the reCAPTCHA):
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured, and your message could not be sent.');
}
});
});
});
The autoload.php comes directly from the Google Github, and I didn't make any changes:
<?php
/* An autoloader for ReCaptcha\Foo classes. This should be required()
* by the user before attempting to instantiate any of the ReCaptcha
* classes.
*/
spl_autoload_register(function ($class) {
if (substr($class, 0, 10) !== 'ReCaptcha\\') {
/* If the class does not lie under the "ReCaptcha" namespace,
* then we can exit immediately.
*/
return;
}
/* All of the classes have names like "ReCaptcha\Foo", so we need
* to replace the backslashes with frontslashes if we want the
* name to map directly to a location in the filesystem.
*/
$class = str_replace('\\', '/', $class);
/* First, check under the current directory. It is important that
* we look here first, so that we don't waste time searching for
* test classes in the common case.
*/
$path = dirname(__FILE__).'/'.$class.'.php';
if (is_readable($path)) {
require_once $path;
}
/* If we didn't find what we're looking for already, maybe it's
* a test class?
*/
$path = dirname(__FILE__).'/../tests/'.$class.'.php';
if (is_readable($path)) {
require_once $path;
}
});
I would really appreciate your help!
Okay, I fixed it. One reason it wasn't working was that I had to enable allow_url_fopen in php.ini.
Then I completely changed the code to get rid of that autoload.php and the class error. I didn't change app.js. The working mailer.php now looks like this:
<?php
// If the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// If the Google Recaptcha box was clicked
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=MYKEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
$obj = json_decode($response);
// If the Google Recaptcha check was successful
if($obj->success == true) {
$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"]);
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 = "I-removed-this#for-now.com";
$subject = "New message from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\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. Check your email address.";
}
}
// If the Google Recaptcha check was not successful
else {
echo "Robot verification failed. Please try again.";
}
}
// If the Google Recaptcha box was not clicked
else {
echo "Please click the reCAPTCHA box.";
}
}
// If the form was not submitted
// Not a POST request, set a 403 (forbidden) response code.
else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>

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