PHP Form - Email sent to address from users multiple choice - php

I have built a PHP form, but want an email to be sent to whatever country the user chooses on a dropdown.
E.g. If they choose UK on dropdown, send an email to our UK account. If they choose US, send to our US account etc...
The entire form is working perfectly at the moment, I just need this little feature to work then it would be perfect. Thank you for looking, its appreciated!
This is my code so far:-
<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');
// configure
// an email address that will be in the From field of the email.
$from = 'A new client has registered their details <noreply#emailaddress.com>';
// an email address that will receive the email with the output of the form
$sendTo = '<scott#emailaddress.com>';
// subject of the email
$subject = 'New Registered Form:';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = [
'firstname' => 'First Name', 'lastname' => 'Last Name', 'company' => 'Company', 'email' => 'Email Address', 'jobrole' => 'Job Role',
'postcode' => 'Postcode', 'country' => 'Country',
];
// message that will be displayed when everything is OK :)
$okMessage = 'Thank you for registering.';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
// ReCaptch Secret
$recaptchaSecret = 'AAAA';
// 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 ( ! empty($_POST))
{
// validate the ReCaptcha, if something is wrong, we throw an Exception,
// i.e. code stops executing and goes to catch() block
if ( ! isset($_POST['g-recaptcha-response']))
{
throw new \Exception('ReCaptcha is not set.');
}
// do not forget to enter your secret key from https://www.google.com/recaptcha/admin
$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost);
// we validate the ReCaptcha field together with the user's IP address
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if ( ! $response->isSuccess())
{
throw new \Exception('ReCaptcha was not validated.');
}
// everything went well, we can compose the message, as usually
$emailText = "This person has registered their details \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 = [
'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 = ['type' => 'success', 'message' => $okMessage];
}
}
catch (\Exception $e)
{
$responseArray = ['type' => 'danger', 'message' => $e->getMessage()];
}
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'];
}
?>
Thank you very much in advance!!
Scott Geere

Personally I would do something like this:
switch ($_POST['country']):
case 'UK':
$sendTo = '<UK#emailaddress.com>';
break;
case 'US';
$sendTo = '<US#emailaddress.com>';
break;
default:
$sendTo = '<scott#emailaddress.com>';
endswitch;
Which means you could change:
// an email address that will receive the email with the output of the form
//$sendTo = '<helena#dropbox.com>,<l.stone#emeraldcolour.com>';
$sendTo = '<scott#emailaddress.com>';
To:
// an email address that will receive the email with the output of the form
//$sendTo = '<helena#dropbox.com>,<l.stone#emeraldcolour.com>';
switch ($_POST['send_to']):
case 'UK':
$sendTo = '<UK#emailaddress.com>';
break;
case 'US';
$sendTo = '<US#emailaddress.com>';
break;
default:
$sendTo = '<scott#emailaddress.com>';
endswitch;
Please do not forget: never trust the user. So do not just do stuff on $_POST data, make sure you validate the given input before you use it.
Another side note:
Instead of using this raw code in yours, you could make it a function (so you can reuse it somewhere else as well).
For example:
function getSendToEmail($country)
{
switch ($country):
case 'UK':
return '<UK#emailaddress.com>';
break;
case 'US';
return '<US#emailaddress.com>';
break;
default:
return '<scott#emailaddress.com>';
endswitch;
}
// an email address that will receive the email with the output of the form
//$sendTo = '<helena#dropbox.com>,<l.stone#emeraldcolour.com>';
$sendTo = $this->getSendToEmail($_POST['country']);
Documentation:
http://php.net/manual/en/control-structures.switch.php // Switch
http://php.net/manual/en/functions.user-defined.php // Functions
http://php.net/manual/en/filter.examples.validation.php // Validation

if (isset($_POST['country'])) {
$country = $_POST['country'];
if ($country === 'France') {
$sendTo = 'france#emailadress.com';
} elseif ($country === 'England') {
$sendTo = 'england#emailadress.com';
}
}
You can put it before the mail function.
You can also use an array like that:
$emailList = [
'France' => 'france#emailadress.com',
'England' => 'england#emailadress.com'
];
if (isset($_POST['country'])) {
// Get email from the key
$sendTo = $emailList[$_POST['country']];
}

Related

Get form data from one wordpress function to another while using a restApi in a custom plugin

i have two rest api end points for the Calculator and another for the email submission.
i want to include the data from calculator to the email handler function.
Calculator Handler:
// function for the endpoint for form
add_action('rest_api_init', 'create_rest_endpoint');
function create_rest_endpoint() {
// Create endpoint for front end to connect to WordPress securely to post form data
register_rest_route('bohio/v1', 'submit', array(
'methods' => 'POST',
'callback' => 'handle_query',
'permission_callback' => '__return_true'
));
}
// callback method
function handle_query($data) {
// Handle the form data that is posted
// Get all parameters from form
$output = $data->get_params();
// form fields : service, bed, bath,square_feet,cadence
}
Email handler:
function handle_email($data) {
// Handle the form data that is posted
// Get all parameters from form
$emailData = $data->get_params();
// Set fields from the form
$field_name = sanitize_text_field($emailData['name']);
$field_email = sanitize_email($emailData['email']);
//Check if nonce is valid, if not, respond back with error
if (!wp_verify_nonce($emailData['_wpnonce'], 'wp_rest')) {
return new WP_Rest_Response('Message not sent', 422);
}
else {
// Remove unneeded data from paramaters
unset($emailData['_wpnonce']);
unset($emailData['_wp_http_referer']);
// Send the email message
$headers = [];
// $admin_email = get_bloginfo('admin_email');
$admin_email = get_option('bh_email_sub');
// var_dump($admin_email);
$from_email = get_option('bh_email_sub');
$admin_name = get_option('bh_admin_sub_name');
// $admin_name = get_bloginfo('name');
// Set admin email as recipient email if no option has been set
$recipient_email = $admin_email;
$headers[] = "From: {$admin_name} <{$from_email}>";
$headers[] = "Reply-to: {$field_name} <{$field_email}>";
$headers[] = "Content-Type: text/html";
$subject = "New email submission from {$field_name}";
$message = '';
$message = "<h2>New Email submission from {$field_name}</h2>";
// Loop through each field posted and sanitize it
foreach ($emailData as $label => $value) {
switch ($label) {
case 'message':
$value = sanitize_textarea_field($value);
break;
case 'email':
$value = sanitize_email($value);
break;
default:
$value = sanitize_text_field($value);
}
$message .= '<strong>' . sanitize_text_field(ucfirst($label)) . ':</strong> ' . $value . '<br />';
}
wp_mail($recipient_email, $subject, $message, $headers);
$confirmation_message = "The message was sent successfully!!";
// return $confirmation_message;
return $confirmation_message;
}
}
How would i access the data from handle_query to handle_email and send via email. Both functions lies in the same file of a plugin.

Is there a simple solution to redirect a PHP contact form back to my site? [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
PHP page redirect [duplicate]
(11 answers)
Closed 3 years ago.
So like loads of people on here, I'm new and know just enough coding to be break everything.
I grabbed a contact form template (jscript & PHP mix) and it works, and even only broke the rest of my HTML contact page only a little.
But my concern is that the result of the validation is that it produces just one of two sentences with no link or navigation to return to the contact or index page. As a PHP noob, I'd just like to try to tackle this the right way, which several hours of Googling hasn't helped. (My programming skills are barely beyond if/then statements). So any input or suggestions would be most welcome!
Here's the section that I think leads to the dead end, in the contact.php Thanks!
// an email address that will be in the From field of the email.
$from = '<insert email>';
// an email address that will receive the email with the output of the form
$sendTo = '<insert email>';
// subject of the email
$subject = 'New message from contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'need' => 'Need', 'email' => 'Email', 'message' => 'Message');
$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';
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'];
}
1- You can use html code in your $okMessage:
$okMessage = "Contact form successfully submitted. Thank you, I will get back to you soon!<br><button onclick='history.go(-1);'>Back </button>";
2- You can redirect the visitor to your page;
$responseArray = array('type' => 'success', 'message' => $okMessage);
//strcmp checks if strings are equal, if they are it will redirect the user to the page
if(strcmp($responseArray['type'],'success') == 0)
header("Location: myPage.php");
//or you can give 5 seconds to the user to read your success message then redirect:
header( "Refresh:5; url=http://www.example.com/page2.php");

How to implement a Spamword filter in php contact form and reCaptcha

I 've a contact form with a working reCaptcha on it, but some spam gets through.
I've tried adding a spamword filter I've found in here Spam Filter in Contact Form
. But it doesn't work, any ideas?
EDIT: ( further explanation, noob mistake) The filter scans through the words in the message field and blocks the mail sending If a word is present.
Nowadays I almost have no spam thanks to recaptcha, but there's like 10 mails a
day advertising Prednisone or Viagra. so, Id like to filter those words ir order to avoid receiving that spam
I've tried inserting the solution I've mentioned before but I receive those mails anyways
Here's my code
I've tried putting the code from the previous post in several different places with no luck.
Thanks in advance.
<?php
// require ReCaptcha class
require '../recaptcha-master/src/autoload.php';
//require($_SERVER['DOCUMENT_ROOT'].'/recaptcha-master/src/autoload.php');
// configure
// an email address that will be in the From field of the email.
$from = 'Formulario de contacto <blehblehbleh#somethingsomething.com>';
// an email address that will receive the email with the output of the form
$sendTo = 'InfoPapelCosido <blablabla#somethingsomething.com>';
// subject of the email
$subject = 'Mensaje Nuevo desde la web de PapelCosido';
// 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', 'message' => 'Message');
// message that will be displayed when everything is OK :)
$okMessage = 'Mensaje enviado, a la brevedad nos comunicaremos con usted.';
// If something goes wrong, we will display this message.
$errorMessage = 'Hubo un error al enviar el mensaje, por favor intente mas tarde';
// ReCaptch Secret
$recaptchaSecret = '#######################';
// 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 (!empty($_POST)) {
// validate the ReCaptcha, if something is wrong, we throw an Exception,
// i.e. code stops executing and goes to catch() block
if (!isset($_POST['g-recaptcha-response'])) {
throw new \Exception('ReCaptcha is not set.');
}
// do not forget to enter your secret key from https://www.google.com/recaptcha/admin
$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
// we validate the ReCaptcha field together with the user's IP address
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$response->isSuccess()) {
throw new \Exception('ReCaptcha was not validated.');
}
// everything went well, we can compose the message, as usually
$emailText = "Mensaje desde la web\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,
);
// THIS IS THE CODE FROM THE POST I'VE CITED BEFORE
//TEST SPAM FILTER
// Prevent spammers from using contact form
//Create an array containing the words in the message
$MessageArray = explode(" ", $emailText );
//Get SPAM words from file and store them in an array
$SpamWords = file_get_contents('spamwords.txt');
$SpamArray = explode("\r\n", $SpamWords);
//Cycle through all the words in the message
foreach($MessageArray as $word){
//Check the word for SPAM words, if it is don't send the email
if(in_array($word, $SpamArray)){
echo '<h1>Spam Guard</h1>';
echo '<p>Here in European Community, the Privacy and Electronic Communications Regulations 2003 cover the sending of email marketing. This legislation says that organisations must only send marketing emails to anyone if they have agreed to receive them, except where there is a clearly defined customer relationship.</p>';
echo '<p>It appears that you are attempting to send an unsolicited message (e.g. a marketing message).</p>';
echo '<p>We as an organisation do not send unsolicited messages and we request that you do the same for us.</p>';
echo '<p>If you are not attempting to send an unsolicited message, there may be an error in the system so please accept our apologies.</p>';
die();
}
}
//If we've made it to this point, our message doesn't contain any obvious SPAM words
//END SPAM FILTER
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
}
catch (\Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
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'];
}

Adding PHPMailer Without Composer

I have this contact form but I am confused as to how I can insert PHPMailer (without Composer) into the script?
I am not sure how to properly add it so that way, once it processes and sends the form it alerts the user. I do not have the ability to utilize composer, so I would need to upload PHPMailer into the directory.
<?php
function validateRecaptcha($secret, $clientResponse, $clientIp)
{
$data = http_build_query([
"secret" => $secret,
"response" => $clientResponse,
"remoteip" => $clientIp,
]);
$options = [
"http" => [
"header" =>
"Content-Type: application/x-www-form-urlencoded\r\n".
"Content-Length: ".strlen($data)."\r\n",
"method" => "POST",
"content" => $data,
],
];
$response = file_get_contents(
"https://www.google.com/recaptcha/api/siteverify",
false,
stream_context_create($options)
);
if($response === false)
{
return false;
}
else if(($arr = json_decode($response, true)) === null)
{
return false;
}
else
{
return $arr["success"];
}
}
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($_POST['firstName']))
$errors['firstName'] = 'First Name is required.';
if (empty($_POST['lastName']))
$errors['lastName'] = 'Last Name is required.';
if (empty($_POST['companyName']))
$errors['companyName'] = 'Company Name is required.';
if (empty($_POST['companyAddress']))
$errors['companyAddress'] = 'Company Address is required.';
if (empty($_POST['city']))
$errors['city'] = 'City is required.';
if (empty($_POST['state']))
$errors['state'] = 'State is required.';
if (empty($_POST['emailAddress']))
$errors['emailAddress'] = 'Email Address is required.';
if (empty($_POST['comment']))
$errors['comment'] = 'Comment is required.';
if (empty($_POST['g-recaptcha-response']))
$errors['captcha'] = 'Captcha is required.';
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if(!validateRecaptcha($secret, $_POST['g-recaptcha-response'], $_SERVER["REMOTE_ADDR"]))
{
$errors['recaptcha'] = 'Captcha is required.';
}
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Success!';
}
// return all our data to an AJAX call
echo json_encode($data);
Without autoloader:
<?php
//You shall use the following exact namespaces no
//matter in whathever directory you upload your
//phpmailer files.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Now include the following following files based
//on the correct file path. Third file is required only if you want to enable SMTP.
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
?>
You shall add the following class to initiate the mailer after checking if your query or condition is executed.
<?php
$mail = new PHPMailer(true);
?>
You shall find a nice and simple example at https://github.com/PHPMailer/PHPMailer/blob/master/README.md to start with.
I hope it helps.

Different behavior between Bootstrap 3 and 4 form validation?

I having issues using a Bootstrap form validation library on my form. For some reason, this works really well on Bootstrap 3, but NOT on Bootstrap 4. I am not sure what about BS4 forms is making their behavior be so different.
The biggest (most important difference for me) is that when on Bootstrap 3, the form once validated and submitted, will display the green feedback back on the form itself, to inform the user the their form was successful.
However, When I run this on Bootstrap 4, not only are the validation colors different, but it redirects the browser to the 'contact.php' file, and prints out the message that should be returned back to the contact form as a green rectangle when compared to BS3.
I would really appreciate if someone can explain what might be going on between these two, and how I can fix it.
I've included screenshots and demos of the code below. I apologize in advance that the are not in JFiddle or Codeply, but because they have a dependency on 'RECAPTCHA.
I would especially appreciate if someone could change the above code to work with Bootstrap 4 and its new validation system.
I have also included links here:
BOOTSTRAP 3 Version: (WORKS!) https://bootstrapious.com/tutorial/recaptcha/
BOOTSTRAP 4 Version: (Doesn't Work the same..) https://josephromo.com
and the .php file which won't appear under developer tools:
<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');
// configure
$from = 'Demo contact form <demo#domain.com>';
$sendTo = 'Demo contact form <demo#domain.com>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' =>. 'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable. name => Text to appear in the email
$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';
$recaptchaSecret = '6LfOUysUAAAAAGkGG_hHYN9g_BsNsPY0S9kPdwYP
';
// let's do the sending
try
{
if (!empty($_POST)) {
// validate the ReCaptcha, if something is wrong, we throw an Exception,
// i.e. code stops executing and goes to catch() block
if (!isset($_POST['g-recaptcha-response'])) {
throw new \Exception('ReCaptcha is not set.');
}
// do not forget to enter your secret key in the config above
// from https://www.google.com/recaptcha/admin
$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
// we validate the ReCaptcha field together with the user's IP address
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$response->isSuccess()) {
throw new \Exception('ReCaptcha was not validated.');
}
// everything went well, we can compose the message, as usually
$emailText = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
$headers = array('Content-Type: text/plain; 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'];
}
Ondrej here. I am the author of the https://bootstrapious.com/p/bootstrap-recaptcha tutorial.
Your main problem is that you don't have the JS scripts included correctly:
validatorjs should be validator.js (make sure it is in its location)
both contact.js and validator.js should be included after jQuery.
see console errors
This prevents both validator and contact script from running and you don't get the form's Ajax behaviour, therefore you just get redirected after the form's submission.
After making these changes, check out the browser console if no more errors show there.
Tip: to speed up the loading of the page, move all the scripts just in front of the </body> closing tag.

Categories