2016-06-27 336 views
0

我發現了以下用於處理聯繫表單的代碼,並希望向它們添加錯誤處理和異常。php異常處理異常

HTML表單的外觀:

<div class="contact-form"> 
    <form id="contact-form" action="sendmail.php" method="post" title="Contact Form" role="form"> 
     <div class="col-sm-6"> 
      <div class="form-group"> 
       <label for="contact-name">Name</label> 
       <input type="text" name="name" placeholder="Enter your name..." class="contact-name" id="contact-name"> 
      </div> 
      <div class="form-group"> 
       <label for="contact-email">Email</label> 
       <input type="text" name="email" placeholder="Enter your email..." class="contact-email" id="contact-email"> 
      </div> 
      <div class="form-group"> 
       <label for="contact-subject bold">Subject</label> 
       <input type="text" name="subject" placeholder="Your subject..." class="contact-subject" id="contact-subject"> 
      </div> 
     </div> 
     <div class="col-sm-6"> 
      <div class="form-group"> 
       <label for="contact-message">Message</label> 
       <textarea name="message" placeholder="Your message..." class="contact-message" id="contact-message"></textarea> 
      </div> 
     </div> 
     <div class="col-sm-12 text-center"> 
      <button type="submit" class="btn btn-default sketchFlowPrint" id="submit">Send</button> 
     </div> 
    </form> 
</div> 

sendmail.php樣子:

<?php 

// Email address verification 
function isEmail($email) { 
    return(preg_match("/^[-_.[:alnum:]][email protected]((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email)); 
} 

if($_POST) { 

    // Enter the email where you want to receive the message 
    $emailTo = '[email protected]'; 

    $clientName = addslashes(trim($_POST['name'])); 
    $clientEmail = addslashes(trim($_POST['email'])); 
    $subject = addslashes(trim($_POST['subject'])); 
    $message = addslashes(trim($_POST['message'])); 

    $array = array(); 
    $array['nameMessage'] = ''; 
    $array['emailMessage'] = ''; 
    $array['messageMessage'] = ''; 

    if($clientName == '') { 
     $array['nameMessage'] = 'Please enter your name.'; 
    } 
    if(!isEmail($clientEmail)) { 
     $array['emailMessage'] = 'Please insert a valid email address.'; 
    } 
    if($message == '') { 
     $array['messageMessage'] = 'Please enter your message.'; 
    } 
    if($clientName != '' && isEmail($clientEmail) && $message != '') { 
     // Send email 
    $headers = "From: " . $clientName . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail . "\r\n"; 
    mail($emailTo, $subject . ' (Example - Website)', $message, $headers); 
    } 

    echo json_encode($array); 

} else { 
     header ('location: index.html#contact'); 
} 

?> 

jQuery腳本的樣子:

// Contact form 
$('.contact-form form').submit(function(e) { 
    e.preventDefault(); 

    var form = $(this); 
    var nameLabel = form.find('label[for="contact-name"]'); 
    var emailLabel = form.find('label[for="contact-email"]'); 
    var messageLabel = form.find('label[for="contact-message"]'); 

    nameLabel.html('Name'); 
    emailLabel.html('Email'); 
    messageLabel.html('Message'); 

    var postdata = form.serialize(); 

    $.ajax({ 
     type: 'POST', 
     url: 'sendmail.php', 
     data: postdata, 
     dataType: 'json', 
     success: function(json) { 
      if(json.nameMessage !== '') { 
       nameLabel.append(' - <span class="red error-label"> ' + json.nameMessage + '</span>'); 
      } 
      if(json.emailMessage !== '') { 
       emailLabel.append(' - <span class="red error-label"> ' + json.emailMessage + '</span>'); 
      } 
      if(json.messageMessage !== '') { 
       messageLabel.append(' - <span class="red error-label"> ' + json.messageMessage + '</span>'); 
      } 
      if(json.nameMessage === '' && json.emailMessage === '' && json.messageMessage === '') { 
       form.fadeOut('fast', function() { 
        form.parent('.contact-form').append('<h2 class="text-center"><span class="orange">Thanks for contacting us!</span> We will get back to you very soon.</h2>'); 
       }); 
      } 
     } 
    }); 
}); 

代碼工作非常好的節選爲TWO東西:

  1. 我收到電子郵件,但客戶的電子郵件地址沒有顯示在我的電子郵件上的任何地方,我無法回覆客戶端,我試圖弄亂標題部分,但無法正確(請幫我解決這個問題)。
  2. 我想讓表單讓用戶知道表單是否未被提交。爲此,我將此代碼添加到jQuery腳本的最後一個「如果」功能後:

    其他{ form.fadeOut(「快」,函數(){ form.parent()「接觸形式。」。 append('出錯了!請刷新頁面並重試。'); }); }。

我想補充例外。我想添加這個「其他」功能,只有當用戶沒有填寫所有必填字段時(如果用戶沒有填寫必填字段,表單必須顯示「輸入您的姓名。「或」請輸入一個有效的電子郵件地址。「或」請在輸入字段頂部輸入您的信息「,具體取決於未填寫的字段)。希望這是有道理的。

+0

異常應該只用於特殊情況下(例如郵件服務器壞了:)。不應使用例外情況告訴用戶輸入的電子郵件無效。 –

回答

0

在你的PHP,你應該定義另一對夫婦的變量

1. $my_email = "[email protected]"; //senders email 
2. $subject = "Query from My Domain"; //a subject line 

然後用

mail($_REQUEST['email'],$subject,$message,$headers,"-f{$my_email}"); 

其中

$headers = "From: " . $my_email; 

其實我通常使用

$headers = "From: " . $my_email; 
$headers .= PHP_EOL; 
$headers .= "MIME-Version: 1.0".PHP_EOL; 
$headers .= "Content-Type: multipart/mixed;".PHP_EOL; 
$headers .= " boundary=\"boundary_sdfsfsdfs345345sfsgs\""; 

我不太明白爲什麼你在php中有接收者的電子郵件;這些值應該從您的表格發佈

$field_order_keys = array('name','email','comment');

,然後要求使用$_REQUEST

這將解決發件人的電子郵件問題

我創建了我接觸PHP腳本的通用形式,我通常使用的plunker。它有亂碼和現場檢查等。也許你會發現它很有用(鏈接沒有登陸它,這是聯繫確認。它在上面的PHP)