Different behavior between Bootstrap 3 and 4 form validation? - php

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.

Related

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'];
}

PHP Form - Email sent to address from users multiple choice

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']];
}

My ReCaptcha mailer won't work

I'm fine-tuning this website for a school project, but my ReCaptcha mailer keeps returning an HTTP ERROR 500. Can someone help me and find the problem?
This is the website: http://i385436.hera.fhict.nl/cates/contact.html
I'm guessing the fault is in the two PHP-files: contact.php and autoload.php, which are both pre-made and downloaded (since I'm pretty noob when it comes to PHP). I believe I configured every setting within the files, like getting my reCaptcha keys etc.
This is the code for contact.php:
<?php
// require ReCaptcha class
require('autoload.php');
// configure
$from = 'tgdtom#gmail.com';
$sendTo = 'tgdtom#gmail.com';
$subject = 'Bericht via Cates contactformulier';
$fields = array('name' => 'Naam', 'email' => 'Email', 'phone' => 'Tel.nr.', 'message' => 'Bericht'); // array variable name => Text to appear in the email
$okMessage = 'Uw bericht is met succes verzonden, u krijgt zo snel mogelijk reactie!';
$errorMessage = 'Er is iets fout gegaan met het versturen van uw bericht, probeer het later nog eens of neem telefonisch contact op.';
$recaptchaSecret = '6Lf9ZzUUAAAAAL7qstYlXD8pE8LCvpsDWWlvsW5-';
// 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'];
}
And this is autoload.php:
<?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 hope you guys/girls can find the problems, or have a better alternative for me. Thanks in advance!

How to send data using json and php in body only?

<?php
$emparray = array();
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$name = urldecode($_POST['name']);
$email = filter_var($_POST["email"],FILTER_SANITIZE_EMAIL);
$subject = urldecode($_POST['subject']);
$message = urldecode($_POST['message']);
$message_final = 'Name :-'.$name."\n".'Email Id :-'.$email."\n".'Message :-'.$message;
$to = 'xyz';
if($name!=NULL && $email!=NULL && $subject!=NULL && $message!=NULL)
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emparray =array(
'status' => 0, 'message' => 'Invalid Email Format');
}
else
{
$emparray= mail($to,$subject,$message_final);
$emparray =array(
'status' => 1, 'message' => 'Thank you for writing us,Email sent successfully');
}
}
else
{
$emparray =array(
'status' => 0, 'message' => 'All fields are required');
}
}
else
{
$emparray = array("status" => 0, "message" => "Request Method Not accepted");
}
echo json_encode($emparray,JSON_PRETTY_PRINT,JSON_FORCE_OBJECT);
?>
I am using postman tool for testing. If I send data using headers with key value it goes like body. How to stop this to send data with headers too.
I want if data will send from body then only it should work. If i send it from headers it should prompt me error of cant send data using headers.
Someone tells me about headers_sent function to overcome this issue. But im unable to implement it. please help me this the same.
You have to select body/raw/JSON (application/json).
Hope it works for you.

Categories