2016-09-28 75 views
0
<?php 
// configure 
$from = 'Demo contact form <[email protected]>'; 
$sendTo = '105 Questions <[email protected]>'; 
$subject = 'New message from contact form'; 
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' =>  'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email 
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!'; 
$errorMessage = 'There was an error while submitting the form. Please try again later'; 
// let's do the sending 

try 
{ 
$emailText = "You have new message from the website\n=============================\n"; 

foreach ($_POST as $key => $value) { 

    if (isset($fields[$key])) { 
     $emailText .= "$fields[$key]: $value\n"; 
    } 
} 

mail($sendTo, $subject, $emailText, "From: " . $from); 

$responseArray = array('type' => 'success', 'message' => $okMessage); 
} 
catch (\Exception $e) 
{ 
$responseArray = array('type' => 'danger', 'message' => $errorMessage); 
} 

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { 
$encoded = json_encode($responseArray); 

header('Content-Type: application/json'); 

echo $encoded; 
} 
else { 
echo $responseArray['message']; 
} 

這是我有點困惑一些代碼結束只是},我得到的錯誤。PHP發送頁面加載電子郵件

但是,當我添加?>它的作品,但也發送頁面加載電子郵件。

在另一篇文章中,我讀到他們用isset修復它,但是當我把它放在「配置註釋」之前,電子郵件仍然在頁面加載時發送。

+0

php在頁面加載時運行。你在代碼中沒有任何邏輯來阻止執行'mail()' –

+0

我是否在代碼的開頭添加了「exit」來阻止php運行? – etnuh

+0

檢查提交併在 –

回答

0

基本邏輯 - 除非您處理表單提交而不是頁面加載,否則不要發送消息。

if (isset($_POST['name'])) { //This will not be true on a page load 
    //Your existing script goes here 
}