2011-08-31 131 views
0

我試圖在WordPress主題中包含一個簡單的聯繫表單我爲某人編寫代碼(他們希望它的功能沒有使用任何WP插件,所以我只是使用PHP)。PHP郵件()麻煩

下面是我使用的代碼:

<?php 

include "../../../../wp-blog-header.php"; // include WP to be able to use some options 

if (of_get_option('ss_contact_email', 'no entry')) { // custom WP option 
    $mailto = of_get_option('ss_contact_email', 'no entry'); 
} else { 
    $mailto = get_option('admin_email'); // WP option to get email address of the admin 
}; 

$cc = ""; 
$bcc = ""; 
$subject = "[Contact Form] " .$_POST['subject']. ""; 

$vname = ucwords($_POST['user']); 

$email = $_POST['email']; 

function validateEmail($email) 
{ 
    if(eregi('^[a-zA-Z0-9._-][email protected][a-zA-Z0-9-]+\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,3})?(\.[a-zA-Z]{2,3})?$', $email)) 
     return true; 
    else 
     return false; 
} 


if((strlen($_POST['user']) < 1) || (strlen($email) < 1) || (strlen($_POST['question']) < 1) || validateEmail($email) == FALSE){ 
    $emailerror .= ''; 

    if(strlen($_POST['user']) < 1){ 
     $emailerror .= '<span class="wrong">Please enter your name. </span>'; 
    } 

    if(validateEmail($email) == FALSE || strlen($email) < 1) { 
     $emailerror .= '<span class="wrong">Please enter a valid e-mail address. </span>'; 
    } 

    if(strlen($_POST['message']) < 1){ 
     $emailerror .= '<span class="wrong">Please enter your message. </span>'; 
    } 

} else { 

    $emailerror .= "<span>Your message has been sent. Thank you!</span>"; 

    // NOW SEND THE ENQUIRY 

    $timestamp = date("F j, Y, g:ia"); 

    $messageproper ="\n\n" . 
     "Name: " . 
     ucwords($_POST['user']) . 
     "\n" . 
     "Email: " . 
     $email . 
     "\n" . 
     "Website: " . 
     $_POST['url'] . 
     "\n" . 
     "Subject: " . 
     $_POST['subject'] . 
     "\n" . 
     "Comments: " . 
     "\n" . 
     $_POST['message'] . 
     "\n" . 
     "\n\n" ; 

     $messageproper = trim(stripslashes($messageproper)); 

     mail($mailto, $subject, $messageproper, "From: \"$vname\" <".$_POST['email'].">\nReply-To: \"".ucwords($_POST['user'])."\" <".$_POST['email'].">\nX-Mailer: PHP/" . phpversion()); 

} 
?> 

<?php echo $emailerror; ?> 

錯誤處理似乎很動聽,它返回所有正確的錯誤,但如果所有信息均正確無誤它去,而不是發送和顯示「謝謝你..空白「 信息。

我在同一臺服務器上多次使用過相同的腳本,從來沒有遇到過任何問題,但是這次我偶然發現了一個問題 - 郵件沒有發送,即使它沒有返回錯誤。

我不確定發生了什麼問題。任何人都可以瀏覽代碼並尋找一些明顯的錯誤?

+0

你檢查了服務器日誌,看看'mail'命令是否失敗? – cdeszaq

+0

您可以嘗試在此代碼段中使用像'$ subject'和'$ message'這樣的變量。有兩個原因:在沒有提交表單的情況下,測試會更容易,並且您可以更安全地過濾「POST」數據以保持更安全。 –

回答

1

您使用:

strlen($_POST['question']) < 1 

作爲檢查你的if語句,但是如果使用「消息」作爲替代。如果未設置「問題」,則不會嘗試發送,但也不會打印錯誤。

+0

賓果。太感謝了。總是有人幫助別人看着代碼後,我一直在盯着它,並擺弄它的年齡:) – Justine

+0

它被稱爲'橡膠鴨'。通常只用英文將你的代碼解釋爲無生命的對象可以幫助你找到問題。 –

0

由於電子郵件沒有被髮送,所以很可能PHP在mail()呼叫時正在死亡。你不檢查郵件()的返回值,這是一種糟糕的形式 - 永遠不要假設對外部服務的調用成功。打開錯誤報告,啓用顯示錯誤等...然後再次嘗試聯繫表單。檢查你的服務器日誌,看看有沒有什麼東西顯示在瀏覽器中。

代碼看起來不錯,所以沒有更多的信息,這個問題很可能是無法回答的。