简体   繁体   English

PHP表单:仅填写字段的成功电子邮件

[英]PHP form: Success email with only filled fields

Been struggling with this for some time now. 一直为此苦苦挣扎了一段时间。 Basically I have 6 fields, name, email, phone, location, date and budget. 基本上我有6个字段,名称,电子邮件,电话,位置,日期和预算。 Name and email are the only required fields. 名称和电子邮件是唯一必填字段。 When I get the email I see rest of the fields as well. 收到电子邮件后,我还会看到其余字段。 Is it possible to receive only fields that have been filled? 是否可以仅接收已填写的字段?

Here's the code; 这是代码;

<?php
// get posted data into local variables
$EmailFrom = "email@email.com";
$EmailTo = "email@email.com";
$Subject = "My form";
$Name = Trim(stripslashes($_POST['Name'])); 
$Email = Trim(stripslashes($_POST['Email'])); 
$Phone = Trim(stripslashes($_POST['Phone']));

$Location = Trim(stripslashes($_POST['Location'])); 
$Date = Trim(stripslashes($_POST['Date']));
$Budget = Trim(stripslashes($_POST['Budget'])); 

// validation
$validationOK=true;
if (!$validationOK) {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=#\">";
  exit;
}

$userip = ($_SERVER['X_FORWARDED_FOR']) ? $_SERVER['X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];

// prepare email body text
$Body = "";
$Body .= "Location: "; $Body .= $Location; $Body .= "\n";
$Body .= "Date: "; $Body .= $Date; $Body .= "\n";
$Body .= "Budget: "; $Body .= $Budget; $Body .= "\n";

$Body .= "Name: "; $Body .= $Name; $Body .= "\n";
$Body .= "Email: "; $Body .= $Email; $Body .= "\n";
$Body .= "Phone: "; $Body .= $Phone; $Body .= "\n";
$Body .= "User's IP: ". $userip;

// send email 
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");

// redirect to success page 
if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=#\">";
}
else{
  print "<meta http-equiv=\"refresh\" content=\"0;URL=#\">";
}
?>

Use empty to check if a value was posted or not: 使用empty检查是否发布了值:

$Phone = !empty($_POST['Phone']) ? trim(stripslashes($_POST['Phone'])) : false;

Then later $Phone will be false if it wasn't filled in and you can do this: 然后,如果未填充$Phone它将为false,您可以执行以下操作:

if($Phone)
    $Body .= "Phone: "; $Body .= $Phone; $Body .= "\n";

You can simply do a check to see if the value is there. 您只需检查一下该值是否存在即可。 you could do this: 您可以这样做:

if (!empty($Location) { $Body .= "Location: "; $Body .= $Location; $Body .= "\n"; }

ect ect. 等等。 This is saying if location is not empty then do that code 这就是说,如果位置不为空,则执行该代码

Yes it is, just add a check before you concat the fields to the body like: 是的,只需在将字段合并到正文之前添加一个检查,例如:

if(!$Location)
{
    $Body .= "Location: "; $Body .= $Location; $Body .= "\n";
}
/*You can also use empty like: */
if(!empty($Date))
{
    $Body .= "Location: "; $Body .= $Date; $Body .= "\n";
}
/*Continue here*/
if (isset($_POST['phone'] && !empty($_POST['phone']){
    $phone = $_POST['phone'];
    //add $phone to email body
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM