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
Related
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.
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
}
}
I am using a form-to-email.php for a contact form in my website, but I don't really understand php code.
The ready-to-use form-to-email.php file has a line "redirect to thank you page," and I have to build a thank you page for the action.
But I hope the UX could be easier like a pop-up thank you message instead of another page.
Anyone could help me to create the lines? Thank you very much!!
Below is the complete code of form-to-email.php, the line "header('Location: thank-you.html')" is the redirect path, and I'm wondering is there any way to modify the lines?
<?php
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$agree = $_POST['agree'];
//Validate first
if(empty($name)||empty($visitor_email))
{
echo "Name and email are mandatory!";
exit;
}
if(IsInjected($visitor_email))
{
echo "Bad email value!";
exit;
}
$email_from = 'receiver#gmail.com';//<== update the email address
$email_subject = "letter from customer";
$email_body = "$name\n".
"Message:\n$message\nLINE ID: $line".
$to = "receiver#gmail.com";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: thank-you.html');
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
If you want to use JavaScript, you can use this code to show the message "Thank you for your message" in an alert() box:
Replace header('Location: thank-you.html') with:
echo'
<script>
window.onload = function() {
alert("Thank you for your message");
location.href = "index.php";
}
</script>
';
You can also use below AJAX script to handle it. It will not reload the page and it will give you good user experience. You must include jquery library to work.
$.ajax({
url: "ready-to-use form-to-email.php",
type: "post",
data: {id:xyz},
success: function (response) {
// you will get response from your php page (what you echo or print)
alert('Success') ;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
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.";
}
?>
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.