<?php
// configure
$from = 'Demo contact form <demo#domain.com>';
$sendTo = '105 Questions <myemail#example.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 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';
// let's do the sending
try
{
$emailText = "You have new message from the website\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$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'];
}
This is where I get a little confused some code end with just } and I got errors.
But when I add ?> it works, but also sends an email on page load.
In another post I read they fixed it with isset but when I put it before the "configure comment" an email was still sent on page load.
Basic logic - don't send the message unless you're handling a form submission rather than a page load.
if (isset($_POST['name'])) { //This will not be true on a page load
//Your existing script goes here
}
Related
Apologies, I'm mostly self taught. I'm using the following code live on https://www.poadvisory.com/contact.html and the contact form appears to be working, ReCaptcha as well, but the email never comes. I've spent countless times on the phone with my hosting provider and they claim is a code issue and not a server issue. Surely it's something obvious I don't see. If anyone can help, I'd really appreciate it. I've searched the current questions but don't believe this is a duplicate question.
<?php
require('recaptcha-master/src/autoload.php');
$sendTo = 'Contact Form < my email goes here>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message');
$okMessage = 'Contact form successfully submitted. Thank you, We will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
$recaptchaSecret = 'removed';
error_reporting(E_ALL & ~E_NOTICE);
try {
if (!empty($_POST)) {
if (!isset($_POST['g-recaptcha-response'])) {
throw new \Exception('ReCaptcha is not set.');
}
$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$response->isSuccess()) {
throw new \Exception('ReCaptcha was not validated.');
}
$emailText = "You have a new message from your 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' => $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'];
}
How can I configure the variables $from & $subject on top so that the email the server sends me uses those values instead of static text?
<?php
// configure
$from = 'Demo contact form <demo#domain.com>';
$sendTo = 'Demo contact form <demo#domain.com>'; // Add Your Email
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'subject' => 'Subject', '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';
// let's do the sending
try
{
$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'];
}
I want $from to use the Name value and $subject to use the Subject value.
Use the following:
# checks if the 'name' key has been $_POST'ed
$from = isset($_POST['name'])?$_POST['name']:$from;
# checks if the 'subject' key has been $_POST'ed
$subject = isset($_POST['subject'])?$_POST['subject']:$subject;
On submitting a form I receive a status code of 202 (response received, email is queued for delivery), with "Form successfully sent" but the email never gets sent.
I've tried re-creating my API key, and have not found an explanation for this behavior from the API.
Is there a workaround to this scenario?
<?php
require("sendgrid-php/sendgrid-php.php");
// an email address that will be in the From field of the email.
$from = 'Demo contact form <test#example.com >';
// an email address that will receive the email with the output of the form
$to = 'Demo contact form <test#example.com>';
// subject of the email
$name = $_POST['name'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'email' => 'Email', 'phone' => 'Phone', 'subject' => 'Subject', 'message' => 'Message');
// 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');
$content = "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])) {
$content .= "$fields[$key]: $value\n";
}
}
/* All the necessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
*/
// Send email
//mail($to, $subject, $content, implode("\n", $headers));
//recaptcha-response
$recaptcha_secret = "6LfK7ygUAAAAAIYzE6mbqdxbmuroi4gJWqdIpmBu";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
if($response["success"] === true){
$from = new SendGrid\Email("Nami19", "namitajamwal19#gmail.com");
// $subject = "Sending with SendGrid is Fun";
// $subject = $_POST['subject'];
$subject= "You have got mail!";
$to = new SendGrid\Email("Example User", "etest549#gmail.com");
$content = new SendGrid\Content("text/html", "
Email : {$email}<br>
Name: {$name}<br>
Subject : {$subject}<br>
Message : {$message}
");
// $content = $_POST["content"];
// $content = $_POST['content'];
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$apiKey = ('SG.4J8IyicKTRqOcu7rOUmJXQ.mLk27ighheFPG4wDF63b5JboXvpGJFZMe');
$sg = new \SendGrid($apiKey);
$sg_response = $sg->client->mail()->send()->post($mail);
echo $sg_response->statusCode();
print_r($sg_response->headers());
echo $sg_response->body();
echo "Form Submit Successfully.";
}else{
echo "You are a robot";
}
// $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'];
}
*/
?>
my contact form keeps getting spam everyday. Not sure why. Here is contact-process.php to process a submission:
<?php
// configure
$from = 'webmaster#example.com';
$sendTo = 'Message from <myemail#mydomain.com>';
$subject = "Contact Form: $name";
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in the email
$human = intval($_POST['humans']);
$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';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// let's do the sending
try
{
$emailText = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
header('Location: /thank-you.php');
}
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'];
}
//Check if simple anti-bot test is correct
if(!empty($_POST['humans'])) {
// it's spam
} else {
// it's human
}
I have no idea why this is happening, I also set up a honeypot as well. Also the emails are coming in as being sent from hostname, not from the individual email addresses themselves.
Thanks for the help guys.
Please forgive me if this is a dumb question, as I am new to php. I did some c++ years ago and are dabbling in c# with Unity.
I am trying to get a working html / js / php contact form working with reCaptcha. The form works well if the captcha is checked, and the 'success' message is displayed. If the captch is not checked, I want to display a message and not send the form email. The code snippet below works insofar as the email is NOT sent if the captcha is not ticked, but it does not display the message. Can anyone help?
$okMessage = 'Contact form successfully submitted. Thank you, we will get back to you soon!';
$captchaMessage = 'There was an error while submitting the form. Please check the captcha box.';
$spamMessage = 'There was an error while submitting the form. Spamers not welcome.';
$captcha = $_POST['g-recaptcha-response'];
try
{
//Sanitise Inputs
$emailText = "You have new message from contact form\n=============================\n";
$emailText .= "First Name: " . #trim(stripslashes($_POST['name'])). "\n";
$emailText .= "Last Name: " . #trim(stripslashes($_POST['surname'])). "\n";
$emailText .= "Company: " . #trim(stripslashes($_POST['company'])). "\n";
$emailText .= "Email: " . #trim(stripslashes($_POST['email'])). "\n";
$emailText .= "Message: " . #trim(stripslashes($_POST['message'])). "\n";
if(!$captcha){
$responseArray = array('type' => 'danger', 'message' => $captchaMessage);
exit;
}
$secretKey = "secret_key";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
$responseArray = array('type' => 'danger', 'message' => $spamMessage);
} else {
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
}
Your exit stop the script. So the message cant be displayed.
if(!$captcha){
$responseArray = array('type' => 'danger', 'message' => $captchaMessage);
}
else
{
$secretKey = "secret_key";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
$responseArray = array('type' => 'danger', 'message' => $spamMessage);
} else {
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
}
// Here the script continue