PHP表单:仅包含填充字段的成功电子邮件

时间:2012-06-08 00:52:11

标签: php forms

现在已经挣扎了一段时间了。基本上我有6个字段,名称,电子邮件,电话,位置,日期和预算。名称和电子邮件是唯一必填字段。当我收到电子邮件时,我也会看到其他字段。是否可以仅接收已填写的字段?

这是代码;

<?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=#\">";
}
?>

4 个答案:

答案 0 :(得分:1)

使用empty检查是否发布了值:

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

如果没有填写,$Phone以后if($Phone) $Body .= "Phone: "; $Body .= $Phone; $Body .= "\n"; 将是假的,你可以这样做:

{{1}}

答案 1 :(得分:0)

您只需检查一下该值是否存在即可。你可以这样做:

if (!empty($Location) { $Body .= "Location: "; $Body .= $Location; $Body .= "\n"; }
等等。这就是说,如果位置不为空,那么执行该代码

答案 2 :(得分:0)

是的,只需在将字段连接到正文之前添加一个检查,如:

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*/

答案 3 :(得分:-1)

if (isset($_POST['phone'] && !empty($_POST['phone']){
    $phone = $_POST['phone'];
    //add $phone to email body
}