PHP:不要通过电子邮件发送空白的表单字段

时间:2011-06-28 05:52:45

标签: php forms email

目前我正在制作一个在线查询表格,其中包含一系列非强制性字段。

如果未填写非强制性表单字段,我希望将其设置为不会在已处理的电子邮件中显示。

例如;如果有人没有输入他们的电话号码,“电话:$ atelephone”组件不会通过。

if ($atelephone != '') { 
echo "Telephone: ".$atelephone;  
}

我认为代码应该包含上面的内容,尽管我正在努力连接点。任何帮助将不胜感激。 (我希望这是有道理的。)

<?php 

// Base form items

$asender = $HTTP_POST_VARS['name'] ." <". $HTTP_POST_VARS['email'] .">";
$asubject = "Email Enquiry: ".$HTTP_POST_VARS['subject'];
$arecipient = "recipient@websiteaddress.com.au";

/*******************************************************/
// Mail form variables //

$aname = $HTTP_POST_VARS['name'];
$aemail = $HTTP_POST_VARS['email'];
$atelephone = $HTTP_POST_VARS['telephone'];
$asuburb = $HTTP_POST_VARS['suburb'];
$aenquiry = $HTTP_POST_VARS['enquiry'];

mail("$arecipient","$asubject", 
"
===========================================
Please note: this is an email 
generated from the Website.
=========================================== 

Name: $aname
Email: $aemail
Telephone: $atelephone
Suburb: $asuburb

Message:
$aenquiry 

================================ ","FROM:$asender"); 

header('Location: /thank-you.php');

?>

2 个答案:

答案 0 :(得分:1)

Hm,遍历POST数组,如果该字段为空,则不要添加它..

类似的东西:

$acceptedInputs = array('name', 'email', etc.);
$spacesBA = array('message'=>array(1,2)); //Spaces before/after, first is before, second is after.  Default is none.

$emailBits = array();

foreach ($_POST as $name=>$value)
{
    if (!in_array($name, $acceptedInputs)) //Don't want them to submit unknown fields
        continue;
    if (!empty($value))
        $emailBits[] = 
str_repeat("\n",(isset($spacesBA[$name][0])?$spacesBA[$name][0]:0) /* Add before lines */
 . $name . ' : ' . $value . 
str_repeat("\n",(isset($spacesBA[$name][1])?$spacesBA[$name][1]:0)); /*Add after lines */
}
$emailBody = "
===========================================
Please note: this is an email 
generated from the Website.
=========================================== 
";
$emailBody .= implode("\n",$emailBits);
$emailBody .= "

================================ ";

答案 1 :(得分:1)

你走在正确的轨道上。最后一步是在最终消息中输入一个字符串:

$_POST['telephone'] ?  
  $telephoneString = "Telephone: ".$_POST['telephone'] ."\n" : 
  $telephoneString = "";

(字符串末尾的\n创建换行符。)

然后,在消息中输出字符串。它将是空的,或不是。

  "foo bar baz
  ===========================================".
  $nameString.
  $emailString.
  $telephoneString.
  $suburbString;

修改

这可能对单个表单字段更有效。但是,为了优雅,我更喜欢@mazzzzzz的解决方案。