2015-04-23 80 views
0

因此,我已經構建了此電子郵件表單,如果未提交名稱或/和電子郵件,應該顯示錯誤消息'名稱和電子郵件是必需的'。但是,如果他們是我收到相同的消息。這怎麼解決?PHP - 在沒有錯誤時提交錯誤信息

<?php 
if(!isset($_POST['submit-enquiry'])) 
{ 
    //This page should not be accessed directly. Need to submit the form. 
    echo "error; you need to submit the form!"; 
} 
$name = $_POST['name']; 
$guest_email = $_POST['email']; 
$mobile = $_POST['mobile']; 
$message = $_POST['enquiry-message']; 

//Validate first 
if(empty($name)||empty($guest_email)) 
{ 
    echo '<script language="javascript">'; 
    echo 'alert("Name and email are mandatory")'; 
    echo '</script>'; 
    exit; 
} 

if(IsInjected($visitor_email)) 
{ 
    echo '<script language="javascript">'; 
    echo 'alert("Bad Email Value")'; 
    echo '</script>'; 
    exit; 
} 

$email_from = $guest_email;//<== update the email address 
$email_subject = "Enquiry from $name"; 
$email_body = "Name: $name. \n". "Mobile: $mobile .\n". "Message:  $message. \n"; 

$to = "my_email";//<== update the email address 
$headers = "From: $email_from \r\n"; 
$headers .= "Reply-To: $guest_email \r\n"; 
//Send the email! 
mail($to,$email_subject,$email_body,$headers); 
//done. redirect to thank-you page. 
header('Location: enquiry.php'); 

// Function to validate against any email injection attempts 
function IsInjected($str) 
{ 
    $injections = array('(\n+)', 
      '(\r+)', 
      '(\t+)', 
      '(%0A+)', 
      '(%0D+)', 
      '(%08+)', 
      '(%09+)' 
     ); 
    $inject = join('|', $injections); 
    $inject = "/$inject/i"; 
    if(preg_match($inject,$str)) 
    { 
    return true; 
    } 
    else 
    { 
    return false; 
    } 
} 

?> 

的fprm的HTML:

<div id="enquiry-form"> 
        <form method="post" name="enquiry-form" action="" target="_self"> 
         <span class="short-input" id="name"> 
          <h6>name</h6> 
          <input type="text" name="name"> 
         </span> 
         <span class="short-input" id="mobile"> 
          <h6>mobile</h6> 
          <input type="text" name="mobile"> 
         </span> 
         <span class="long-input" id="email"> 
          <h6>e-mail</h6> 
          <input type="text" name="email"> 
         </span> 
         <span class="long-input" id="enquiry-message"> 
          <h6>enquiry</h6> 
          <textarea name="enquiry-message"></textarea> 
         </span> 

       </div> 
       <div id="contact-info"> 
        <h2>Contact Details</h2> 
       </div> 
       <button type="submit" id="submit-enquiry" name="submit-enquiry">send</button> 
       </form> 
+0

你能做一個$ _POST轉儲嗎? 你確定你的表單沒有使用GET而不是POST嗎? 也許向我們展示表單的HTML? – Spode

回答

0

嘗試

if($name=='' || $guest_email=='') 

在某些情況下空洞會導致意想不到的結果。我的經驗讓我說,對於表單驗證,最好通過這種方式檢查變量是否爲空。然後你檢查變量的內容(例如,看看它是否是一個有效的電子郵件),所以這對我來說足夠安全。 如果你的代碼仍然不起作用,那麼有必要做進一步的調查。

+0

這不提供問題的答案。要批評或要求作者澄清,請在其帖子下方留言。 –

+0

你是對的。當我在電話中時,我錯誤地發佈了我的答案,並且缺少部分文本。 :) –

0
if(empty(trim($name)) || empty(trim($guest_email)))