Conditionally send email from contact form with different variables - php

I have a contact form that has certain conditions. If the user clicks the radio button saying they are a Consumer, a new range of questions appears. If they click that they have an image to upload, the image uploader appears.
As it is now, the email that is sent to us and to the user shows all of the fields, even if blank. It has the potential to get confusing if the person didn't click that they were a consumer, only to see 3 extra questions in their email confirmation that they didn't even see on the form.
I have it set up so there is a $success that should send the message to us and the user without all of the consumer questions, $successConsumer that should send the message to us and the user with consumer questions, but without the image, and $successOther that should send the message to us and the user with consumer questions AND the image.
I have tried including the variable in with the if statements, i.e
if ($_FILES["uploaded_file"]["size"] == 0) {
$successOther = mail($email_address, $subject, $messageOther, $headers);
$successOther = mail($email_address, $subject, $messageOther2, $headers);
header("Location: thanks.php");
}
with no luck, as well as using eval(), return(), and exit() in similar fashions. It either doesn't work at all, or it will send me all 6 messages, not just 2. I'm sure there is a way to do this, but I'm just not grasping how it's done. I've tried multiple Google searches, but I'm coming up with nothing. Any help or direction is really appreciated!
<?php
//Collect contact form data
//Check Special Field
//Email ASC & Webmaster
//Email Sender
//Redirect to thank you page
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
/******** CONTACT DATA **********/
$name = stripslashes($_POST['name']);
$company = stripslashes($_POST['company']);
$address = stripslashes($_POST['address']);
$city = stripslashes($_POST['city']);
$state = stripslashes($_POST['state']);
$zipcode = stripslashes($_POST['zipcode']);
$country = stripslashes($_POST['country']);
$website = $_POST['website'];
$phone = stripslashes($_POST['phone']);
$fax = stripslashes($_POST['fax']);
$email = stripslashes($_POST['contact']);
$Referred = stripslashes($_POST['referred']);
$CustomerType = stripslashes($_POST['CustomerType']);
$Comments = stripslashes($_POST['comments']);
$ConsumerHelp = stripslashes($_POST['ConsumerHelp']);
$UPC = stripslashes($_POST['UPC']);
$uploaded_file = ($_FILES['uploaded_file']);
if ($_FILES["uploaded_file"]["size"] == 0) {
header("Location: thanks.php");
}
else {
// there is a file
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["uploaded_file"]["name"]);
$extension = end($temp);
$userImage = $_FILES["uploaded_file"]["name"];
$location = str_replace(' ', '_', $location);
if ((($_FILES["uploaded_file"]["type"] == "image/gif")
|| ($_FILES["uploaded_file"]["type"] == "image/jpeg")
|| ($_FILES["uploaded_file"]["type"] == "image/jpg"))
&& ($_FILES["uploaded_file"]["size"] < 2300000 )
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["uploaded_file"]["error"] . "<br>";
} else {
header("Location: thanks.php");
if (file_exists("uploads/" . $_FILES["uploaded_file"]["name"])) {
echo $_FILES["uploaded_file"]["name"] . " already exists. ";
} else {
$location = "uploads/" . $temp[0].".".time().".".$extension;
$location = str_replace(' ', '_', $location);
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"], $location);
echo "Stored in: " . $location;
}
}
} else {
header("Location: sorry.php");
exit ();
}
}
/******** NOT CONSUMER EMAIL ASC & WEBMASTER **********/
$message = "
-----------------------------------------------------------------------------
Information Inquiry
-----------------------------------------------------------------------------
$name has visited the web site and would like some information.
The details they entered on the website are:
Name: $name
Company: $company
Address: $address
City: $city
State: $state
Zip Code: $zipcode
Country: $country
Website: $website
Phone: $phone
Fax: $fax
Email: $email
Referred to web site: $Referred
CustomerType: $CustomerType
Comments: $Comments
I need help with: $ConsumerHelp
UPC code or Item #: $UPC
Image: http://www.example.com/test/$location
(If the consumer sent the form without attaching an image, the link above will not have the file name at the end - just ignore it.)
Kind Regards,
";
$email_address = "example#example.com";
$subject = "Information Inquiry";
$headers = "From: $name <$email>";
$message = str_replace("\r",'',$message); //fixes postfix php bug that double spaces messages
/******** NOT CONSUMER EMAIL SENDER **********/
$message2 = "
-----------------------------------------------------------------------------
Re: Information Inquiry
-----------------------------------------------------------------------------
Thank you $name for visiting the web site. We will be using the details you entered to contact you.
Name: $name
Company: $company
Address: $address
City: $city
State: $state
Zip Code: $zipcode
Country: $country
Website: $website
Phone: $phone
Fax: $fax
Email: $email
Referred to web site: $Referred
CustomerType: $CustomerType
Comments: $Comments
I need help with: $ConsumerHelp
UPC code or Item #: $UPC
Image: $userImage
Kind Regards,
";
$email_address2 = "$email";
$subject2 = "Re: Information Inquiry";
$headers2 = "From: Example <example#example.com>";
$message2 = str_replace("\r",'',$message2); //fixes postfix php bug that double spaces messages
/******** CONSUMER - WITH IMAGE - EMAIL ASC & WEBMASTER **********/
$messageConsumer = "
-----------------------------------------------------------------------------
Information Inquiry
-----------------------------------------------------------------------------
$name has visited the web site and would like some information.
The details they entered on the website are:
Name: $name
Company: $company
Address: $address
City: $city
State: $state
Zip Code: $zipcode
Country: $country
Website: $website
Phone: $phone
Fax: $fax
Email: $email
Referred to web site: $Referred
CustomerType: $CustomerType
Comments: $Comments
I need help with: $ConsumerHelp
UPC code or Item #: $UPC
Image: http://www.example.com/test/$location
Kind Regards,
";
$email_address = "example#example.com";
$subject = "Information Inquiry";
$headers = "From: $name <$email>";
$messageConsumer = str_replace("\r",'',$messageConsumer); //fixes postfix php bug that double spaces messages
/******** CONSUMER - WITH IMAGE - EMAIL SENDER **********/
$messageConsumer2 = "
-----------------------------------------------------------------------------
Re: Information Inquiry
-----------------------------------------------------------------------------
Thank you $name for visiting the web site. We will be using the details you entered to contact you.
Name: $name
Company: $company
Address: $address
City: $city
State: $state
Zip Code: $zipcode
Country: $country
Website: $website
Phone: $phone
Fax: $fax
Email: $email
Referred to web site: $Referred
CustomerType: $CustomerType
Comments: $Comments
I need help with: $ConsumerHelp
UPC code or Item #: $UPC
Image: $userImage
Kind Regards,
";
$email_address2 = "$email";
$subject2 = "Re: Information Inquiry";
$headers2 = "From: <example#example.com>";
$messageConsumer2 = str_replace("\r",'',$messageConsumer2); //fixes postfix php bug that double spaces messages
/******** CONSUMER - NO IMAGE - EMAIL ASC & WEBMASTER **********/
$messageOther = "
-----------------------------------------------------------------------------
Information Inquiry
-----------------------------------------------------------------------------
$name has visited the web site and would like some information.
The details they entered on the website are:
Name: $name
Company: $company
Address: $address
City: $city
State: $state
Zip Code: $zipcode
Country: $country
Website: $website
Phone: $phone
Fax: $fax
Email: $email
Referred to web site: $Referred
CustomerType: $CustomerType
Comments: $Comments
I need help with: $ConsumerHelp
UPC code or Item #: $UPC
Kind Regards,
";
$email_address = "example#example.com";
$subject = "Information Inquiry";
$headers = "From: $name <$email>";
$messageOther = str_replace("\r",'',$messageOther); //fixes postfix php bug that double spaces messages
/******** CONSUMER - NO IMAGE - EMAIL SENDER **********/
$messageOther2 = "
-----------------------------------------------------------------------------
Re: Information Inquiry
-----------------------------------------------------------------------------
Thank you $name for visiting the web site. We will be using the details you entered to contact you.
Name: $name
Company: $company
Address: $address
City: $city
State: $state
Zip Code: $zipcode
Country: $country
Website: $website
Phone: $phone
Fax: $fax
Email: $email
Referred to web site: $Referred
CustomerType: $CustomerType
Comments: $Comments
I need help with: $ConsumerHelp
UPC code or Item #: $UPC
Kind Regards,
";
$email_address2 = "$email";
$subject2 = "Re: Information Inquiry";
$headers2 = "From: <example#example.com>";
$messageOther2 = str_replace("\r",'',$messageOther2); //fixes postfix php bug that double spaces messages
$success = mail($email_address, $subject, $message, $headers);
$successConsumer = mail($email_address, $subject, $messageConsumer, $headers);
$successOther = mail($email_address, $subject, $messageOther, $headers);
//conditionally send message2, no need to check success on this one
if (strpos($email,'#aol.com') == false) {
mail($email_address2, $subject2, $message2, $headers2);
$successConsumer = mail($email_address, $subject, $messageConsumer2, $headers);
$successOther = mail($email_address, $subject, $messageOther2, $headers);
}
if (!$success) {
// What happens when the form does not validate
header("Location: sorry.php");
die ();
} else {
// Your code here to handle a successful verification
// header("Location: thanks.php");
$success;
}
?>
Edit
I tried replacing the if statement with the code below... I don't get any mail now. Any thoughts?
if ( isset($_POST['CustomerType']) )
{
if ( $_POST['CustomerType'] === 'Consumer')
{
$success = mail ($headersCoastal, $subjectCoastal, $messageConsumer, $email_address);
$success = mail ($headersUser, $subjectUser, $messageConsumer2, $email);
// header("Location: thanks.php");
}
else
{
$success = mail ($headersCoastal, $subjectCoastal, $messageOther, $email_address);
$success = mail ($headersUser, $subjectUser, $messageOther2, $email);
// header("Location: thanks.php");
}
};
Edit
<?php
// Vars
$name = filter_input( INPUT_POST, 'name' );
$email = filter_input( INPUT_POST, 'email' );
//$customer = filter_input( INPUT_POST, 'customer' );
$company = filter_input( INPUT_POST, 'company' );
$address = filter_input( INPUT_POST, 'address' );
$city = filter_input( INPUT_POST, 'city' );
$state = filter_input( INPUT_POST, 'state' );
$zipcode = filter_input( INPUT_POST, 'zipcode' );
$country = filter_input( INPUT_POST, 'country' );
$website = filter_input( INPUT_POST, 'website' );
$phone = filter_input( INPUT_POST, 'phone' );
$fax = filter_input( INPUT_POST, 'fax' );
$email = filter_input( INPUT_POST, 'email' );
$Referred = filter_input( INPUT_POST, 'Referred' );
$CustomerType = filter_input( INPUT_POST, 'CustomerType' );
$Comments = filter_input( INPUT_POST, 'comments' );
$ConsumerHelp = filter_input( INPUT_POST, 'ConsumerHelp' );
$UPC = filter_input( INPUT_POST, 'UPC' );
$uploaded_file = ($_FILES['uploaded_file']);
$to_asc = 'example#gmail.com';
$to_webmaster = 'example#example.com';
$to_user = $email;
$subject = 'Information Inquiry';
$from = 'ACME WIDGET COMPANY';
$headers = "From: " . $to_asc . "\r\n";
$headers .= "Reply To: " . $to_asc . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= '<p>Thank you ' . $name . ' for visiting the Coastal Pet Products web site. We will be using the details you entered to contact you.</p>';
// Check for customer status.
if ( isset( $CustomerType ) )
{
if ( $CustomerType == 'Consumer')
{
$message .= '<p>Name: $name
</br>Company: $company
</br>Address: $address
</br>City: $city
</br>State: $state
</br>Zip Code: $zipcode
</br>Country: $country
</br>Website: $website
</br>Phone: $phone
</br>Fax: $fax
</br>Email: $email
</br>Referred to web site: $Referred
</br>CustomerType: $CustomerType
</br>Comments: $Comments
</br>I need help with: $ConsumerHelp
</br>UPC code or Item #: $UPC';
header ("Location: thanks.php");
}
else
{
$message .= '<p>Name: $name
</br>Company: $company
</br>Address: $address
</br>City: $city
</br>State: $state
</br>Zip Code: $zipcode
</br>Country: $country
</br>Website: $website
</br>Phone: $phone
</br>Fax: $fax
</br>Email: $email
</br>Referred to web site: $Referred
</br>CustomerType: $CustomerType
</br>Comments: $Comments';
header ("Location: thanks.php");
}
}
else // Input was not selected at all.
{
header("Location: sorry.php");
die ();;
}
// You can look/set other conditions as you go to further assemble a specific message to the user/admins.
// Now back to a chunk that all users see.
//$message .= '<p>Oh well, it\'s all good in the hood!</p>';
//echo $message;
// Mail the message.
if (mail($to_user, $subject, $message, $headers))
{
// Mail to user was sent. Now send email to admin(s).
mail($to_asc, $subject, $message, $headers);
}
Final Edit
I was able to get everything working with the code below. The only changes I need to make now are minor, such as setting it so the email that goes to the user says that it is from us, not them. Not a huge deal though! :)
<?php
// Vars
$name = stripslashes($_POST['name']);
$company = stripslashes($_POST['company']);
$address = stripslashes($_POST['address']);
$city = stripslashes($_POST['city']);
$state = stripslashes($_POST['state']);
$zipcode = stripslashes($_POST['zipcode']);
$country = stripslashes($_POST['country']);
$website = $_POST['website'];
$phone = stripslashes($_POST['phone']);
$fax = stripslashes($_POST['fax']);
$email = stripslashes($_POST['contact']);
$Referred = stripslashes($_POST['referred']);
$CustomerType = stripslashes($_POST['CustomerType']);
$Comments = stripslashes($_POST['comments']);
$ConsumerHelp = stripslashes($_POST['ConsumerHelp']);
$UPC = stripslashes($_POST['UPC']);
$uploaded_file = ($_FILES['uploaded_file']);
$to_asc = 'example#example.com';
$to_webmaster = 'example#example.com';
$to_user = $email;
$subject = 'Information Inquiry';
$from = 'My Company';
$headers = "From: $name <$email>";
//$headers .= "Reply To: " . $to_asc . "\r\n";
$message .= "Thank you, " . $name . ", for visiting the web site. We will be using the details you entered to contact you.";
if ($_FILES["uploaded_file"]["size"] == 0) {
header("Location: thanks.php");
}
else {
// there is a file
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["uploaded_file"]["name"]);
$extension = end($temp);
$userImage = $_FILES["uploaded_file"]["name"];
$location = str_replace(' ', '_', $location);
if ((($_FILES["uploaded_file"]["type"] == "image/gif")
|| ($_FILES["uploaded_file"]["type"] == "image/jpeg")
|| ($_FILES["uploaded_file"]["type"] == "image/jpg"))
&& ($_FILES["uploaded_file"]["size"] < 2300000 )
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["uploaded_file"]["error"] . "<br>";
} else {
header("Location: thanks.php");
if (file_exists("uploads/" . $_FILES["uploaded_file"]["name"])) {
echo $_FILES["uploaded_file"]["name"] . " already exists. ";
} else {
$location = "uploads/" . $temp[0].".".time().".".$extension;
$location = str_replace(' ', '_', $location);
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"], $location);
echo "Stored in: " . $location;
}
}
} else {
header("Location: sorry.php");
exit ();
}
}
// Check for customer status.
if ( isset( $CustomerType ) )
{
if ( $CustomerType == 'Consumer' && ($_FILES["uploaded_file"]["size"] == 0) )
{
$message .= "
Name: $name
Company: $company
Address: $address
City: $city
State: $state
Zip Code: $zipcode
Country: $country
Website: $website
Phone: $phone
Fax: $fax
Email: $email
Referred to web site: $Referred
CustomerType: $CustomerType
Comments: $Comments
I need help with: $ConsumerHelp
UPC code or Item #: $UPC";
header ("Location: thanks.php");
}
if ( $CustomerType == 'Consumer' && ($_FILES["uploaded_file"]["size"] >= 1) )
{
$message .= "
Name: $name
Company: $company
Address: $address
City: $city
State: $state
Zip Code: $zipcode
Country: $country
Website: $website
Phone: $phone
Fax: $fax
Email: $email
Referred to web site: $Referred
CustomerType: $CustomerType
Comments: $Comments
I need help with: $ConsumerHelp
UPC code or Item #: $UPC
Image: http://www.example.com/test/$location";
header ("Location: thanks.php");
}
if ( $CustomerType !== 'Consumer')
{
$message .= "
Name: $name
Company: $company
Address: $address
City: $city
State: $state
Zip Code: $zipcode
Country: $country
Website: $website
Phone: $phone
Fax: $fax
Email: $email
Referred to web site: $Referred
CustomerType: $CustomerType
Comments: $Comments";
header ("Location: thanks.php");
}
}
else // Input was not selected at all.
{
header("Location: sorry.php");
die ();;
}
// Mail the message.
if (mail($to_user, $subject, $message, $headers))
{
// Mail to user was sent. Now send email to admin(s).
mail($to_asc, $subject, $message, $headers);
}

Give this a try. I'm not able to test the actual mail() function at work. However, when I echo out $message i'm getting what I would expect in an email.
HTML:
<!doctype html>
<head>
<title>Email Form</title>
</head>
<body>
<form id="myForm" action="submit.php" method="post">
<fieldset>
<legend>Customer Form</legend>
<label for="name">Name</label>
<input type="text" id="name" name="name" placeholder="Robert Paulson" />
<label for="email">Email</label>
<input type="email" id="email" name="email" placeholder="robert.paulson#email.com" />
</fieldset>
<fieldset>
<p>Are you a customer?</p>
<input type="radio" name="customer" id="customerY" value="yes" /><label for="customerY">Yes</label>
<input type="radio" name="customer" id="customerN" value="no" /><label for="customerN">No</label>
</fieldset>
<fieldset>
<input type="submit" value="Submit" />
</fieldset>
</form>
</body>
</html>
PHP: (submit.php)
<?php
// Vars
$name = filter_input( INPUT_POST, 'name' );
$email = filter_input( INPUT_POST, 'email' );
$customer = filter_input( INPUT_POST, 'customer' );
$to_asc = 'asc#email.com';
$to_webmaster = 'webmaster#email.com';
$to_user = $email;
$to_isCustomer = 'is.customer#email.com';
$to_isNotCustomer = 'not.customer#email.com';
$subject = 'Information Inquiry';
$from = 'ACME WIDGET COMPANY';
$headers = "From: " . $to_asc . "\r\n";
$headers .= "Reply To: " . $to_asc . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= '<p>Hi ' . $name . ', thanks for whatev.</p>';
// Check for customer status.
if ( isset( $customer ) )
{
if ( $customer == 'yes')
{
$message .= '<p>Because you are a valued coustomer, we\'ll respond ASAP!</p>';
}
else
{
$message .= '<p>Because you are not a coustomer, we\'ll respond sometime - you know, before the house burns down.</p>';
}
}
else // Input was not selected at all.
{
$message .= '<p>Because you didn\'t check an option - I don\'t know what to call you.</p>';
}
// You can look/set other conditions as you go to further assemble a specific message to the user/admins.
// Now back to a chunk that all users see.
$message .= '<p>Oh well, it\'s all good in the hood!</p>';
echo $message;
// Mail the message.
if (mail($to_user, $subject, $message, $headers))
{
// Mail to user was sent. Now send email to admin(s).
mail($to_asc, $subject, $message, $headers);
}
For example, this is what renders if the user does not select a customer option at all:
Hi bob, thanks for whatev.
Because you didn't check an option - I don't know what to call you.
Oh well, it's all good in the hood!

This might take some re-working, but I would try to cut down the amount of re-doing things.
By that I mean have 1 mail() call.
I'm greatly over-simplifying here, but this should give you an idea of what I'm talking about. In essence, you would piece together the message rather than repeat yourself over and over with different mail calls/settings.
NOTE: be sure to sanitize all data!
HTML:
<form action="bla.php" method="post">
<input type="text" name="name" />
<input type="email" name="email" />
<radio name="customer" value="yes" />
<radio name="customer" value="no" />
<input type="submit" value="submit" />
</form>
PHP:
<?php
$to = '';
$submit = '';
$message = '';
$headers = 'SOME_HEADER_VALUES';
$name = $_POST['name'];
$email = $_POST['email'];
$admin_eamil = 'admin#email.com';
$message .= 'Hello, thanks for whatev.';
if ( isset[$_POST['customer']) )
{
if ( $_POST['customer'] === 'yes')
{
$subject = 'Re: Hi Customer';
$message .= 'Glad you\'re a customer!';
}
else
{
$subject = 'Re: Meh, whatever';
$message .= 'We are ignoring you since you are not a customer';
}
}
else
{
...
}
// whatever else conditions you need could go here
...
$message .= 'Glad we got that all cleared up.';
if (mail($to, $subject, $message, $headers))
{
mail($admin_eamil, $subject, $message, $headers);
}

Related

Adding CC to headers of php email script and formatting the php response code

I have a working email script. Now I want to add the senders email in CC, so they get a copy of the email as a result. So I added the $headers part to it and in the email on the receiving end it shows as being CC'd, but the CC'd email does not actually get the email. Any thoughts?
<?php
if($_POST) {
$yourEmail = "myemail#business.com";
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$headers = 'From:' . $email . "\r\n" . 'Cc:' . $email . "\r\n";
$responseRefresh = "Redirecting in 5 seconds.<br>";
$responseFillData = "Please fill all the data.<br>";
$responseValidEmail = "Please enter valid email.<br>";
$responseCompleted = "Form successfully submitted.<br>";
$responseFailed = "Form failed to be submitted.<br>";
$response = "" . $responseRefresh;
$hasError = false;
if($fname == "" || $lname == "" || $email == "" || $phone == "") {
$hasError = true;
$response = $responseFillData . $response;
}
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9+-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i", $email)) {
$hasError = true;
$response = $responseValidEmail . $response;
}
if($hasError) {
header("refresh:5;url=index.html#contact");
echo $response;
return false;
}
$text = "Voornaam: $fname \n
Familienaam: $lname \n
E-mailadres: $email \n
Telefoonnummer: $phone \n
Bericht: \n
$message";
if(mail($yourEmail, $fname . " " . $lname . " sent a message via de DDW website", $text, $headers)) {
$response = $responseCompleted . $response;
}
else {
$response = $responseFailed . $response;
}
header("refresh:5;url=index.html#contact");
echo $response;
}
?>
Next to that, I also want to format the response message. I tried adding some html elements to the message, but that does not seem to work. How can I add my image in the 'success' response?
Example:
$responseCompleted = "Form successfully submitted. <img src="http://www.ddw-sanitair.be/img/vink.png"><br>";

recaptcha not sending email after verify in php

<?php
if(isset($_POST['submit']))
{
$email=$_POST['email'];
$comment=$_POST['comment'];
$captcha=$_POST['g-recaptcha-response'];
if(!$captcha)
{
echo 'Please check the the captcha form.';
}
$response=file_get_contents("https://www.google.com/recaptcha/api/sitev erify?secret="secretkey" &response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
header('Location:http://mywebsite.com/.errordocs/404.html');
}
else
{
header('Location:http://mywebsite.com/thankyou.php');
}
}
if (isset ($_POST['Side_Form'])){
$name = $_POST['name'];
$last = $_POST['last'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
// Build the email (replace the address in the $to section with Enjoy's contact e-mail)
$to = 'somebody#somewhere.com';
$subject = "Main Contact Form";
$message = "Name: $name
Email: $email
Phone: $phone
Comments: $comments";
$headers = "From: $email \r\n";
mail($to, $subject, $message, $headers);
}
?>
The problem is when the recaptcha is verified on the form, it displays the checkmark, user can click submit, but I get a blank screen and email doesn't send. Any help is Greatly appreciated, have been working on this for about 3 weeks.
your currently redirecting before actually sending the email. here is your code restructured. also fixed the recaptcha response processing
<?php
if (isset($_POST['submit'])){
$email = $_POST['email'];
$comment = $_POST['comment'];
$captcha = $_POST['g-recaptcha-response'];
if (! $captcha){
echo 'Please check the the captcha form.';
exit();
}else{
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $secretkey . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
$responseKeys = json_decode($response,true);
if (intval($responseKeys["success"]) !== 1){
header('Location:http://mywebsite.com/.errordocs/404.html');
exit();
}else{
if (isset($_POST['Side_Form'])){//not sure what this is, hopefully you do :-)
$name = $_POST['name'];
$last = $_POST['last'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
// Build the email (replace the address in the $to section with Enjoy's contact e-mail)
$to = 'somebody#somewhere.com';
$subject = "Main Contact Form";
$message = "Name: $name
Email: $email
Phone: $phone
Comments: $comments";
$headers = "From: $email \r\n";
mail($to,$subject,$message,$headers);
header('Location:http://mywebsite.com/thankyou.php');
exit();
}
}
}
}
?>

Processing my form with required fields php

I'm just starting to learn php, so I suspect this is going to be an easy one. I want to create a form that has one required field (name) and requires at least one of two other fields (email or phone number). This is what I came up with:
<?php
if (isset($_POST["submit"])) {
if (empty($_POST["name"]) or {empty($_POST["email"]) and empty($_POST["number"])}) {
$error = "Your name and a contact method are required fields";}
else {
$name = $_POST["name"];
$email = $_POST["email"];
$number = $_POST["number"];
$contactmethod = $_POST["contactmethod"];
$subject = $_POST["subject"];
$location = $_POST["location"];
$message = $_POST["message"];
$subjectline = "You have a message from $name!";
$header = "From: $email";
$body = <<<EMAIL
Name: $name,
Number: $number,
Email: $email,
Subject: $subject,
Location: $location,
Contact method: $contactmethod.
$message
EMAIL;
mail("MYEMAILADDRESS", $subjectline, $body, $header);
}
}
?>
I have no clue what's wrong.
Thanks
Your problem: You used { and } in a if-statement.
Next time you can use a PHP code checker like http://phpcodechecker.com/
Correct code:
if (empty($_POST["name"]) or (empty($_POST["email"]) and empty($_POST["number"]))) {
$error = "Your name and a contact method are required fields";}
else {
$name = $_POST["name"];
$email = $_POST["email"];
$number = $_POST["number"];
$contactmethod = $_POST["contactmethod"];
$subject = $_POST["subject"];
$location = $_POST["location"];
$message = $_POST["message"];
$subjectline = "You have a message from $name!";
$header = "From: $email";
$body = <<<EMAIL
Name: $name,
Number: $number,
Email: $email,
Subject: $subject,
Location: $location,
Contact method: $contactmethod.
$message
EMAIL;
mail("MYEMAILADDRESS", $subjectline, $body, $header);
}
}
?>
You can't use braces interchangeably with parentheses.
if (empty($_POST["name"]) or {empty($_POST["email"]) and empty($_POST["number"])}) {
it needs to use parentheses
if (empty($_POST["name"]) or (empty($_POST["email"]) and empty($_POST["number"]))) {

email address in from field on contact form not showing in email header as "from"

iv added the header field in the form code but when i receive the email, the "from" field in the email shows a garbled code and not the email address of the person who sent the message. This is my message processing code:
<?php session_start();
if(isset($_POST['Submit'])) { if( $_SESSION['chapcha_code'] == $_POST['chapcha_code'] && !empty($_SESSION['chapcha_code'] ) ) {
$youremail = 'I removed my address for privacy on stack overflow';
$fromsubject = 'A message from your website';
$title = $_POST['title'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$mail = $_POST['mail'];
$address = $_POST['address'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "From: $nome <$mail>\r\n";
$to = $youremail;
$mailsubject = 'Message received from'.$fromsubject.' Contact Page';
$body = $fromsubject.'
The person that contacted you is '.$fname.' '.$lname.'
Address: '.$address.'
'.$city.', '.$zip.', '.$country.'
Phone Number: '.$phone.'
E-mail: '.$mail.'
Subject: '.$subject.'
Message:
'.$message.'
|---------END MESSAGE----------|';
echo "Thank you for your feedback. I will contact you shortly if needed.<br/>Go to <a href='/index.php'>Home Page</a>";
mail($to, $subject, $body);
unset($_SESSION['chapcha_code']);
} else {
echo 'Sorry, you have provided an invalid security code';
}
} else {
echo "You must write a message. </br> Please go to <a href='/contact.php'>Contact Page</a>";
}
?>
You declared your ^From: header` here:
$headers = "From: $nome <$mail>\r\n";
But it isn't used when you call mail()
mail($to, $subject, $body);
You need to pass $headers as fourth parameter. Else the headers won't take effect
mail($to, $subject, $body, $headers);
You haven't declared $nome anywhere in your code nor $mail in:
$headers = "From: $nome <$mail>\r\n";
And besides that, as this comment mentions, you didn't pass the header into the mail function. See the fourth parameter of the mail function.

PHP - Mail Form Content - how to add CC field?

I have used this PHP mail script for a while now and it served me well... I need to ask a few things.
Right now, it just sends an email to me with the information posted.
then it just Echo's back to the user if it was submitted successfully or not.
How can I add a CC field to send the user some direction on what to do next?
thanks
if (isset($_POST['submit'])) {
if (!$_POST['name'] | !$_POST['email'])
{
echo"<div class='error'>Error<br />You did not fill in a required field, please review your form and correct the missing information.</div>";
}
else
{
$name = $_POST['name'];
$email = $_POST['email'];
$email2 = $_POST['email2'];
$legal = $_POST['legal'];
$legal2 = $_POST['legal2'];
$address = $_POST['address'];
$address2 = $_POST['address2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
$yoursite = "See Me Shine Models";
$youremail = $email;
$subject = "Website Model Form";
$message = "$name would like you to contact them about See Me Shine Models.
Contact PH: $phone
Email: $email
Email2: $email2
Legal: $legal
Legal2: $legal2
Address: $address
Address2: $address2
City: $city
State: $state
Zip: $zip
Phone: $phone
Comments: $comments";
$email3 = "myaddress#me.com";
mail($email3, $subject, $message, "From: $email");
echo"<div class='thankyou'>Thank you for contacting us,<br /> we will respond as soon as we can.</div>";
}
}
You need to specify fourth argument of headers:
$xheaders = "";
$xheaders .= "From: Name-Here. <$email>\n";
$xheaders .= "X-Sender: <$email>\n";
$xheaders .= "X-Mailer: PHP\n"; // mailer
$xheaders .= "X-Priority: 1\n"; //1 Urgent Message, 3 Normal
$xheaders .= "Content-Type:text/html; charset=\"iso-8859-1\"\n";
$xheaders .= "Cc: cc_email#example.com\n";
.................
mail($email3, $subject, $message, $xheaders);
Or see this tutorial:
Send email with CC(Carbon Copy) & BCC(Blind Carbon Copy)

Categories