Sending email to multiple adressess PHP - php

I have an HTML form where you can enter your email and a message.
After you submit this form i would like an email to be sent to my email (fixed) and to the email that is filled in trough the form.
I got my email to work but i can't seem to get the email from my HTML form into the send list in PHP. Any suggestions?
Code (html):
<form id="contact-form" method="post" action="js/contact.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Vul hier je email adres in" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">message</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Vul hier een eventuele opmerking of message in." rows="4" required="required" data-error="Please,leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Versturen">
</div>
</div>
</div>
</form>
Code PHP:
<?php
$from = 'info#mywebsite';
$sendTo = 'myemail#gmail.com'; //Here the email from the form should be added
$subject = 'Nieuwe reservering';
$fields = array('kosten' => 'kosten' , 'name' => 'Naam', 'surname' => 'Achternaam', 'phone' => 'Telefoonnummer', 'kamer' => 'Kamer', 'aankomst' => 'aankomst', 'vertrek' => 'vertrek', 'email' => 'Email', 'message' => 'Bericht');
$okMessage = 'Je bericht is verzonden!';
$errorMessage = 'Oei er ging iets fout, geeft niks. Probeer het later opnieuw.';
error_reporting(E_ALL & ~E_NOTICE);
try {
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText ="<table>";
$emailText .="<p>Bedankt voor uw reservering, hieronder de ingevulde info:</p><br><br>";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "<tr><td>{$fields[$key]}</td>";
$emailText .= "<td>$value</td></tr>";
}
}
$emailText .="<br><br><p>Voor vragen of wijzigingen mail naar: info#bmyemail</p>";
$emailText .="</tr></table>";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers = array('Content-type:text/html;charset=UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e){
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
} else {
echo $responseArray['message'];
}

You can specify all recipients like this: (check official guideline here)
$sendTo = 'myemail#gmail.com, abc#example.com, xyz#example.com'; // note the comma
//actual message
$message = "Message Content";
mail($sendTo, $subject, $message));
Hope it helps! :)

After your email is done, you just need to send it twice :
<?php
mail($addr1, $subject, $message, $header);
mail($addr2, $subject, $message, $header);
?>
You can also concatenate differents addresses (I've managed to send a mail to different addresses by changing my input to a textarea and writing one address per line).
Good luck!

Related

Why my Bootstrap alert not showing in my form? AJAX

My form is supposed to show an alert, either "success" if the message was sent successfully or "danger" if there was an error, for example incorrect captcha or captcha completion.
The problem is that it doesn't show the alert with the CSS style, it only shows the close button and the error. Could someone tell me what is wrong?
Bootstrap version: 4.1 && PHP version 8.1
HTML:
<form id="contact_form" class="contact-form" action="contact_form/contact_form.php" method="post">
<div class="messages"></div>
<div class="controls two-columns">
<div class="fields clearfix">
<div class="left-column">
<div class="form-group form-group-with-icon">
<input id="form_name" type="text" name="name" class="form-control" placeholder="" required="required" data-error="Write your name.">
<label>Name</label>
<div class="form-control-border"></div>
<div class="help-block with-errors"></div>
</div>
<div class="form-group form-group-with-icon">
<input id="form_email" type="email" name="email" class="form-control" placeholder="" required="required" data-error="Put your email.">
<label>Email</label>
<div class="form-control-border"></div>
<div class="help-block with-errors"></div>
</div>
<div class="form-group form-group-with-icon">
<input id="form_subject" type="text" name="subject" class="form-control" placeholder="" required="required" data-error="Write a Subject.">
<label>Subject</label>
<div class="form-control-border"></div>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="right-column">
<div class="form-group form-group-with-icon">
<textarea id="form_message" name="message" class="form-control" placeholder="" rows="7" required="required" data-error="And... your message?."></textarea>
<label>Message</label>
<div class="form-control-border"></div>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="g-recaptcha" data-theme="dark" data-sitekey="6Lc9oSQcAAAAAMd-JXG26NP1iNzIeNZatd_Eetrv"></div>
<input type="submit" class="button btn-send" value="Send">
</div>
</form>
Code JS:
$(function () {
$('#contact_form').validator();
$('#contact_form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact_form/contact_form.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact_form').find('.messages').html(alertBox);
$('#contact_form')[0].reset();
}
}
});
return false;
}
});
});
CODE PHP:
<?php
// configure
$from = ''; // Replace it with Your Hosting Admin email. REQUIRED!
$sendTo = ''; // Replace it with Your email. REQUIRED!
$subject = '';
$fields = array('name' => 'Name', 'email' => 'Email', 'subject' => 'Subject', 'message' => 'Message'); // array variable name => Text to appear in the email. If you added or deleted a field in the contact form, edit this array.
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
//your site secret key
$secret = '';
//get verify response data
$c = curl_init('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$verifyResponse = curl_exec($c);
$responseData = json_decode($verifyResponse);
if($responseData->success):
try
{
$emailText = nl2br("You have new message from Contact Form\n");
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= nl2br("$fields[$key]: $value\n");
}
}
$headers = array('Content-Type: text/html; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
else:
$errorMessage = 'Robot verification failed, please try again.';
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
endif;
else:
$errorMessage = 'Please click on the reCAPTCHA box.';
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
endif;
Thanks in advance.

PHP Contact Form GDPR Validation

I have a contact form that I manage to make work.
The form has some fields, the reCaptcha and a consent check box.
The PHP code is like this:
if($_POST)
{
$to_Email = "contact#blabla.com"; //Replace with recipient email address
$subject = 'Form contact'; //Subject line for emails
//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"]) || !isset($_POST["userprivacy"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'It is necessary to fill in all the fields and validate the terms and conditions box.'));
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 = $_POST["userSubject"];
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
$customer_privacy = filter_var($_POST["userprivacy"], 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);
}
$message_Body = "<strong>Name: </strong>". $user_Name ."<br>";
$message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
$message_Body .= "<strong>Empresa: </strong>". $user_Subject ."<br>";
$message_Body .= "<strong>Message: </strong>". $user_Message ."<br>";
$message_Body .= "<strong>Message: </strong>". $customer_privacy ."<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' => 'Hola '.$user_Name .' Gracias por contactanos, en breve nos pondremos en contacto contigo.'));
die($output);
}
}
And the HTML like this:
<form class="getin_form wow fadeInUp">
<div class="col-sm-12" id="result"></div>
<div class="row">
<div class="col-md-12 col-sm-12">
<div class="form-group bottom45">
<input class="form-control" type="text" placeholder="Nombre" name="user_name" required>
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group bottom45">
<input class="form-control" type="email" name="user_email" placeholder="Correo Eletronico" required>
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group bottom45">
<input class="form-control" type="text" name="last_name" placeholder="Empresa">
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group bottom45">
<textarea class="form-control" name="user_message" placeholder="Mensaje"></textarea>
</div>
<div class="col-md-12 col-sm-12">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form action="?" method="POST">
<div class="g-recaptcha" data-sitekey="aaaaaaaaaaaaaaaaaaaaaaaaaaa"></div>
</div>
<div>
<div class="col-md-1 checker" id="uniform-customer_privacy">
<input type="checkbox" value="0" required name="customer_privacy" autocomplete="off">
</div>
<div><span>He leído y acepto los <span style="text-decoration: underline;"><strong>Términos y condiciones</strong></span> de blablabla.</span></div>
</div>
<div class="col-sm-12">
<button type="button" class="button defaulthole" id="submit_btn">Enviar</button>
</div>
</div>
</form>
When I fill out the form and press send, I still get the error that it is not completed.
I don't know if I'm putting any variables wrong - I don't really understand why it's not working.

PHP Contact Form Variations with Variables depending on Form

I was wondering someone could help me out with a best practice to achieve the following.
Please bare in mind I have very little experience with PHP, and am doing something more of a favour for a friend's company (his current developer is travelling and not due back until March).
He's put together 3 basic landing pages (each relevant to an industry), each has the exact same form on. The problem at the moment is the way they work is they all post to the same email address and have the same subject line (they all post to contact.php).
So what I'd like to do is add an IF statement, and perhaps put output a different $subject and $sendTo so they can be unique depending on each form. I've been having a look around and don't really want to have to create a new form and implement that, hopefully, I can just adjust what's here.
Here's contact.php
<?php
// an email address that will be in the From field of the email.
$from = 'Contact form <creative#email.com>';
// an email address that will receive the email with the output of the form
$sendTo = 'Contact form <creative#email.com>';
// subject of the email
$subject = 'Contact form enquiry from the Creative Services Landing Page';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'marketing' => 'Marketing');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
And here's the HTML
<form class="container" id="contact-form" method="post" action="contact.php" role="form">
<div class="row justify-content-md-center">
<div class="col-12 col-md-5 col-lg-4">
<div class="messages"></div>
</div>
<div class="col-12 col-md-5 col-lg-4">
<div class="form-group">
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Your first name is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-12 col-md-5 col-lg-4">
<div class="form-group">
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Your surname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-12 col-md-5 col-lg-4">
<div class="form-group">
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-12 col-md-5 col-lg-4">
<div class="form-group">
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="A valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-12 col-md-3 col-lg-2">
<button type="submit" class="btn btn--primary">Send</button>
</div>
</div>
</form>
Any help would be hugely appreciated!
You could give to every form a different value via $_GET:
<form class="container" id="contact-form" method="post" action="contact.php?landing_page=1" role="form">
And then depending of $_GET['landing_page'] value set $from, $sendTo and $subject variables:
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'marketing' => 'Marketing');
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
if (isset($_GET['landing_page']))
{
if ($_GET['landing_page'] == 1)
{
$from = 'Contact form <creative#email.com>';
$sendTo = 'Contact form <creative#email.com>';
$subject = 'Contact form enquiry from the Creative Services Landing Page';
}
elseif($_GET['landing_page'] == 2)
{
$from = 'Contact form <creative#email.com>';
$sendTo = 'Contact form <creative#email.com>';
$subject = 'Contact form enquiry from the Creative Services Landing Page';
}
elseif($_GET['landing_page'] == 3)
{
$from = 'Contact form <creative#email.com>';
$sendTo = 'Contact form <creative#email.com>';
$subject = 'Contact form enquiry from the Creative Services Landing Page';
}
else
{
throw new \Exception('Invalid landing_page value');
}
}
else
{
throw new \Exception('Invalid landing_page value');
}
/*
* LET'S DO THE SENDING
*/

Attempting to create Automated Email Form with Visual Studio and PHP

I am building a website that has a form that when the submit button is selected it is supposed to send an automated email. I have been able to get the HTML portion of the form to send properly. The verification also works. The issue is no physical email is being sent. How should I error test this?
The form is built in Visual Studio using html. Here is the code for the form
<div class="one_half">
<form action="demo-contact.php method="post" id="sky-form" class="sky-form">
<h2 class="uppercase"><strong>Contact Form</strong></h2>
<fieldset>
<div class="row">
<section class="col col-6">
<label class="label">Name</label>
<label class="input"> <i class="icon-append icon-user"></i>
<input type="text" name="name" id="name">
</label>
</section>
<section class="col col-6">
<label class="label">E-mail</label>
<label class="input"> <i class="icon-append icon-envelope-alt"></i>
<input type="email" name="email" id="email">
</label>
</section>
</div>
<section>
<label class="label">Subject</label>
<label class="input"> <i class="icon-append icon-tag"></i>
<input type="text" name="subject" id="subject">
</label>
</section>
<section>
<label class="label">Message</label>
<label class="textarea"> <i class="icon-append icon-comment"></i>
<textarea rows="4" name="message" id="message"></textarea>
</label>
</section>
<section>
<label class="checkbox">
<input type="checkbox" name="copy" id="copy">
<i></i>Send a copy to my e-mail address</label>
</section>
</fieldset>
<footer>
<button type="submit" class="button">Send message</button>
</footer>
<div class="message"> <i class="icon-ok"></i>
<p>Your message was successfully sent!</p>
</div>
</form>
</div>
Additonally there is a error check in
$(function()
{
// Validation
$("#sky-form").validate(
{
// Rules for form validation
rules:
{
name:
{
required: true
},
email:
{
required: true,
email: true
},
message:
{
required: true,
minlength: 10
}
},
// Messages for form validation
messages:
{
name:
{
required: 'Please enter your name',
},
email:
{
required: 'Please enter your email address',
email: 'Please enter a VALID email address'
},
message:
{
required: 'Please enter your message'
}
},
// Ajax form submition
submitHandler: function(form)
{
$(form).ajaxSubmit(
{
success: function()
{
$("#sky-form").addClass('submited');
}
});
},
// Do not change code below
errorPlacement: function(error, element)
{
error.insertAfter(element.parent());
}
});
});
The issue I am experiencing is with the php code.
<?php
if( isset($_POST['name']) )
{
$from = "Sender <postmaster#skyvantagemedia.com>";
$to = "Recipient <skyvantage#outlook.com>";
$subject = $_POST['subject'];
$message = $_POST['message'] . "\n\n" . 'Regards, ' . $_POST['name'] . '.';
$host = "mail.skyvantagemedia.com";
//IMPORtANT: This email MUST be same as your FROM address.
$username = "postmaster#skyvantagemedia.com"; //IMPORtANT: This email MUST be same as your FROM address.
//IMPORtANT: This email MUST be same as your FROM address.
$password = "*********";
$headers = 'From: ' . $_POST['name'] . "\r\n" . 'Reply-To: ' . $_POST['email'] . "\r\n" . 'X-Mailer: PHP/' . phpversion();
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
mail($to, $subject, $message, $headers);
if( $_POST['copy'] == 'on' )
{
mail($_POST['email'], $subject, $message, $headers);
}
}
?>
Currently the HTML works but no email is being sent. Any advice on how to error trap the problem would be appreciated.
I am not sure if this will help or work, but here is the default/original PHP that comes with SkyPro.
<?php
session_start();
if( isset($_POST['name']) && strtoupper($_POST['captcha']) == $_SESSION['captcha_id'] )
{
$to = 'example#someEmail.com'; // Replace with your email
$subject = 'Message from website'; // Replace with your $subject
$headers = 'From: ' . $_POST['email'] . "\r\n" . 'Reply-To: ' . $_POST['email'];
$message = 'Name: ' . $_POST['name'] . "\n" .
'E-mail: ' . $_POST['email'] . "\n" .
'Subject: ' . $_POST['subject'] . "\n" .
'Message: ' . $_POST['message'];
mail($to, $subject, $message, $headers);
if( $_POST['copy'] == 'on' )
{
mail($_POST['email'], $subject, $message, $headers);
}
}
?>
Maybe try replacing yours with back to the original and give it a shot. Cheers!

Using reCAPTCHA on contact-form.php

reCaptcha is sending messages without activating the reCaptcha and last night I received over 300 messages a boot.
Help me please how to add so that only sent when the button is activated reCaptcha. Send sends works well but not activation reCaptcha.
To start contact.html within my template I have put this way:
<!-- Start formulario de contacto -->
<div class="row">
<div class="col-md-9">
<h2>Formulario de contacto</h2>
<form action="php/contact-form.php" id="contact-form">
<div class="alert alert-success hidden" id="contact-alert-success">
<strong>Mensaje enviado correctamente!</strong> Muchas gracias, pronto nos pondremos en contacto con usted, normalmente nuestro tiempo de respuesta es inferior a 2 horas.
</div>
<div class="alert alert-danger hidden" id="contact-alert-error">
<strong>Error!</strong> A sucedido un error si lo desea puede contactarnos directamente en XXXX#tize.XXXX
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Nombre <span class="required">*</span></label>
<input type="text"
value=""
data-msg-required="Por favor introduzca su nombre"
class="form-control"
name="name" id="name">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>eMail <span class="required">*</span> </label>
<input type="email"
value=""
data-msg-required="Por favor introduzca su eMail"
data-msg-email="Por favor introduzca un eMail válido"
class="form-control"
name="email"
id="email">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Asunto <span class="required">*</span></label>
<input type="text"
value=""
data-msg-required="Por favor introduzca el asunto"
class="form-control"
name="subject"
id="subject">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Mensaje <span class="required">*</span></label>
<textarea
data-msg-required="Por favor introduzca su mensaje"
rows="10"
class="form-control"
name="message"
id="message"></textarea>
</div>
</div>
</div>
<!-- Start Google Recaptcha -->
<div class="g-recaptcha" data-sitekey="6Lc88P4SAAAAANiT-ZXILUo-ET4xQmbivHy7uHc8"></div><br>
<!-- End Google Recaptcha -->
<div class="row">
<div class="col-md-12">
<input type="submit" value="Enviar mensaje" class="btn btn-primary" data-loading-text="Cargando...">
</div>
</div>
</form>
</div>
<!-- End formulario de contacto -->
And in php form to send the messages have this post with contact-form.php :
<?php
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
// Enter your email address
$to = 'XXXX#tize.XX';
$subject = $_POST['subject'];
if($to) {
$name = $_POST['name'];
$email = $_POST['email'];
$fields = array(
0 => array(
'text' => 'Name',
'val' => $_POST['name']
),
1 => array(
'text' => 'Email address',
'val' => $_POST['email']
),
2 => array(
'text' => 'Message',
'val' => $_POST['message']
)
);
$message = "";
foreach($fields as $field) {
$message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "<br>\n";
}
$headers = '';
$headers .= 'From: ' . $name . ' <' . $email . '>' . "\r\n";
$headers .= "Reply-To: " . $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
if (mail($to, $subject, $message, $headers)){
$arrResult = array ('response'=>'success');
} else{
$arrResult = array ('response'=>'error');
}
echo json_encode($arrResult);
} else {
$arrResult = array ('response'=>'error');
echo json_encode($arrResult);
}
?>
Picture of my form, If anyone wants to see my website please let me know and send you the link. Thank you very much. sending without activating the reCaptcha http://goo.gl/oSLQG9
1.) Using your current provided code <script src='https://www.google.com/recaptcha/api.js'></script> is missing and is required for recaptcha to work.
2.) Per Google's documentation on Re-Captcha, Google will send a response on a verified/non-verified submission in which you must use a $_GET call to evaluate the response for success / fail.
From Google Re-Captcha step 2 - server side integration:
When your users submit the form where you integrated reCAPTCHA, you'll
get as part of the payload a string with the name
"g-recaptcha-response". In order to check whether Google has verified
that user, send a GET request with these parameters:
URL: https://www.google.com/recaptcha/api/siteverify
secret(required) 6LedHvoSAAAAAN4cRa8x1FaVsKPsMrs8SGMqp4ef
response(required) The value of 'g-recaptcha-response'. remoteip The
end user's ip address.
In short - I don't see the required SCRIPT linking in your code provided, I also see no implementation of a $_GET call to Google re-captcha to verifiy success/failure of the re-captcha entered by the user.
Be sure you are implimenting and using the tools/directions provided directly from Google to make your integration located here:
Google Re-Captcha Site
From the code, I can't see link and declaration of private-key and public-key in it.
I myself use this to handle it:
1.Place the google-recaptcha file in a directory.
2.declare on contact.php, as:
require_once('../recpatcha_google.php');
$publickey = '6LcZIfxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$privatekey = '6LcZIf8Sxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
3.to check if user verify and pass the captcha:
$resp = recaptcha_check_answer ($privatekey,$_SERVER['REMOTE_ADDR'],strip_tags($_POST['recaptcha_challenge_field']),strip_tags($_POST['recaptcha_response_field']));
if (!$resp->is_valid) { //if not true ......
................
}
4.call the captcha inside your form, as:
<?php echo recaptcha_get_html($publickey); ?>
Note: Do not forget to register your site with WWW or without WWW to make sure everything runs OK.

Categories