2011-06-28 123 views
1

目前我正在製作一個非強制性的字段集的在線查詢表。PHP:不要通過電子郵件發送表單字段

如果非強制性表單字段沒有填寫出來,我想使它不會在處理過的電子郵件中出現。

例如;如果有人沒有輸入他們的電話號碼,則「電話:$ 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 = "[email protected]"; 

/*******************************************************/ 
// 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'); 

?> 

回答

1

你在正確的軌道上。最後一步是做一個字符串輸入您的最終消息:(該\n字符串的結束使一個換行符)

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

然後,輸出消息中的字符串。它將是空的,或不是。

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

編輯

這可以更好地爲各個表單字段。不過,爲了優雅,我更喜歡@mazzzzzz的解決方案。

+0

我同意我認爲@mazzzzzz解決方案是非常整潔。非常感謝您的解決方案。不幸的是,我想我將不得不生成單獨的表單域。 – Brandrally

+0

@Brandrally - 您可能想檢查的一件事是代碼中的安全性。將原始'post'數據發送到任何地方而不先過濾它通常是一個壞主意。要過濾的是一個全新的問題。 – Ben

+0

非常好的一點 – Ben

1

嗯,通過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 .= " 

================================ "; 
+0

謝謝@mazzzzz上面是一個非常好的解決方案,雖然有問題的查詢表單有200多個字段,因此需要對它進行一些具體的設置。 – Brandrally

+0

意外按下返回。這樣,我可以將答案聚集在標題下方,並在適當的地方添加額外的回報,以使電子郵件更容易閱讀。 – Brandrally

+0

我想你可以創建另一個數組,每個位有多少個返回值,然後在每個循環中添加多少個返回值。 Tbh,與形式,這是唯一實用的解決方案 – Ben