有条件地使用不同变量从联系表单发送电子邮件

时间:2014-05-02 20:11:56

标签: php forms email conditional-statements

我有一个具有一定条件的联系表格。如果用户单击单选按钮表示他们是消费者,则会出现一系列新问题。如果他们点击了他们要上传的图片,则会显示图片上传器。

就像现在一样,发送给我们和用户的电子邮件显示所有字段,即使是空白。如果该人没有点击他们是消费者,那么它有可能让人感到困惑,只是在他们的电子邮件确认中看到他们甚至没有在表单上看到的3个额外问题。

我已经设置好了,所以有一个$ success成功,应该将消息发送给我们和用户,而不是所有消费者的问题,$ successConsumer应该将消息发送给我们和有消费者问题的用户,但没有image和$ successOther应该将消息发送给我们以及有消费者问题和图像的用户。

我尝试将变量包含在if语句中,即

if ($_FILES["uploaded_file"]["size"] == 0) {
     $successOther = mail($email_address, $subject, $messageOther, $headers);
     $successOther = mail($email_address, $subject, $messageOther2, $headers);
     header("Location: thanks.php");
    }

没有运气,以及以类似的方式使用eval(),return()和exit()。它要么根本不起作用,要么它会向我发送所有6条消息,而不仅仅是2.我确信有办法做到这一点,但我只是没有理解它是如何完成的。我尝试了多次谷歌搜索,但我什么也没想到。任何帮助或方向都非常感谢!

<?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;

}

&GT?;

修改 我尝试用下面的代码替换if语句...我现在没有收到任何邮件。有什么想法吗?

     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");
    }
};

修改

<?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);
  }

最终修改 我能够使用下面的代码完成所有工作。我现在需要做的唯一更改是次要的,例如设置它以便发送给用户的电子邮件说它来自我们,而不是他们。虽然不是很大的交易! :)

<?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);
}

2 个答案:

答案 0 :(得分:0)

这可能需要一些重新工作,但我会尽量减少重做的事情。 我的意思是1 mail()来电。

我在这里过分简化了,但这应该会让你知道我在谈论什么。从本质上讲,您可以将消息拼凑在一起,而不是一遍又一遍地重复使用不同的邮件呼叫/设置。

注意:请务必清理所有数据!

<强> 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);
}

答案 1 :(得分:0)

试一试。我无法在工作中测试实际的mail()功能。但是,当我回复$message时,我会收到我在电子邮件中所期望的内容。

<强> 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);
}

例如,如果用户根本没有选择客户选项,则会出现这种情况:

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!