简体   繁体   English

php电子邮件表格。 只想发布填充字段,而不想发布空字段

[英]php email form. Only want to post filled fields and not post empty ones

I have a contact form that looks like this 我有一个接触的形式,看起来像这样

Different form fields will appear based on what the user picks on the "I would like to" select box. 根据用户在“我想”选择框中选择的内容,将出现不同的表单字段。

I want to implement a solution that I found on this site. 我想实施在此站点上找到的解决方案 Basically the php only posts fields that are filled out and does not post fields that are empty. 基本上,PHP仅发布已填写的字段,而不发布为空的字段。 It utilses the following code to achieve it 它使用以下代码来实现它

foreach ($_POST as $Field=>$Value) { 
if($Value != ''){
$body .= "$Field: $Value\n";
}
}

I am not fluent in PHP and wasn't able to apply the solution proposed. 我不精通PHP,也无法应用建议的解决方案。 Would appreciate if someone could help implement the solution into my code to make it post non empty form elements which includes text fields, select boxes and radio groups. 如果有人可以帮助将解决方案实施到我的代码中,使它发布包含文本字段,选择框和单选组的非空表单元素,将不胜感激。

The code for my PHP form processor looks like the following 我的PHP表单处理器的代码如下所示

<?php

$name = $_POST['name'];  
$email_address = $_POST['email'];  
$phone = $_POST['phone'];  
$message = $_POST['message'];  
$p_prefered_day = $_POST['p_prefered_day'];  (radio button)
$session_time = $_POST['session_time'];  (select box)
$p_message = $_POST['p_message'];  
$treatment = $_POST['treatment'];  (select box)
$therapist = $_POST['therapist'];  (select box)
$b_pref_day = $_POST['b_pref_day'];  (radio button)
$b_pref_time = $_POST['b_pref_time'];  (radio button)
$b_message = $_POST['b_message'];  

$to = 'info@zenwebcreative.com.au'; 
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nCompany: $company\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n";
$headers .= "Reply-To: $email_address"; 

mail($to,$email_subject,$email_body,$headers);
return true;            
?>

The HTML code of my form looks like the following 我的表单的HTML代码如下所示

  <form name="sentMessage" id="contactForm" novalidate>                
    <div class="form-group">
      <label>Full Name *</label>
      <input type="text" class="form-control" id="name" required>
    <p class="help-block text-danger"></p>
    </div><!--  end form-group -->

    <div class="form-group">
      <label>Email Address*</label>
      <input type="email" class="form-control" id="email" required>
    <p class="help-block text-danger"></p>
    </div><!--  end form-group -->

    <div class="form-group">
      <label>Contact Number</label>
      <input type="text" class="form-control" id="phone">
    </div> <!-- end form group -->

    <div class="form-group">
    <label>I would like to *</label>
      <select id="select_question" class="form-control">            
        <option selected="selected">Please select</option>
        <option value="question">Ask a question</option>
        <option value="pilates">Attend a pilates class</option>
        <option value="booking">Schedule a booking</option>
      </select>
    </div><!--  end form-group --> 

    <div class="form-group box question">
    <label>Message</label>
      <div class="input-group">                  
        <textarea id="message" class="form-control" rows="7" required></textarea>
        <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
      </div><!--  end input group -->
    <p class="help-block text-danger"></p>
    </div><!--  end form-group --> 

    <div class="box pilates">

      <div class="form-group">
        <label>Prefered day of the week *</label><br>
        <label class="radio-inline">
          <input type="radio" name="p_prefered_day" id="Tue" value="Tuesday">Tuesday
        </label>
        <label class="radio-inline">
          <input type="radio" name="p_prefered_day" id="Thu" value="Thursday">Thursday
        </label>
      </div> <!-- end form group -->

      <div class="form-group">
      <label>Prefered Session you would like to attend? *</label>
        <select class="form-control" id="session_time">
          <option value="4:30 pm">4:30 pm</option>
          <option value="5:30 pm">5:30 pm</option>
          <option value="6:30 pm">6:30 pm</option>
        </select>
      </div><!--  end form-group --> 

      <div class="form-group">
      <label>Additional Comments</label>
        <div class="input-group">                  
          <textarea id="p_message" class="form-control" rows="7" required></textarea>
          <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
        </div><!--  end input group -->
      <p class="help-block text-danger"></p>
      </div><!--  end form-group --> 

    </div><!--  end box pilates -->

    <div class="box booking">

      <div class="form-group">
      <label>What Service Are You Interested In? *</label>
        <select class="form-control" id="services">
          <option value="Manual Therapy">Manual Therapy</option>
          <option value="Sports Physiotherapy">Sports Physiotherapy</option>
          <option value="Dry Needling">Dry Needling</option>
          <option value="Post and Pre operative care">Post and Pre operative care</option>
          <option value="Real Time Ultrasound Imaging">Real Time Ultrasound Imaging</option>
          <option value="Balance and Vestibular treatment">Balance and Vestibular treatment</option>
          <option value="Sports Specific Rehabilitation">Sports Specific Rehabilitation</option>
          <option value="Motor Vehicle Accident">Motor Vehicle Accident</option>
          <option value="Workers Compensation">Workers Compensation</option>            
        </select>
      </div><!--  end form-group --> 

      <div class="form-group">
      <label>Which therapist would you like to see*</label>
        <select class="form-control" id="therapist">
          <option selected="selected">No Preference</option>
          <option value="Kristen">Kristen</option>
          <option value="Tara">Tara</option>        
        </select>
      </div><!--  end form-group --> 

      <div class="form-group">
        <label>Prefered day of the week *</label><br>
        <label class="radio-inline">
          <input type="radio" name="b_pref_day" id="b_Mon" value="Mon-">Mon
        </label>
        <label class="radio-inline">
          <input type="radio" name="b_pref_day" id="b_Tue" value="Tue">Tue
        </label>
        <label class="radio-inline">
          <input type="radio" name="b_pref_day" id="b_Wed" value="Wed">Wed
        </label>
        <label class="radio-inline">
          <input type="radio" name="b_pref_day" id="b_Thu" value="Thu">Thu
        </label>
        <label class="radio-inline">
          <input type="radio" name="b_pref_day" id="b_Fri" value="Fri">Fri
        </label>
      </div> <!-- end form group --> 

      <div class="form-group">
        <label>Prefered time of the day</label><br>
        <label class="radio-inline">
          <input type="radio" name="b_pref_time" id="morning" value="Morning">Morning
        </label>
        <label class="radio-inline">
          <input type="radio" name="b_pref_time" id="afternoon" value="Afternoon">Afternoon
        </label>
      </div> <!-- end form group --> 

      <div class="form-group">
      <label>Addtional Comments</label>
        <div class="input-group">                  
          <textarea id="b_message" class="form-control" rows="7" required></textarea>
          <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
        </div><!--  end input group -->
      <p class="help-block text-danger"></p>
      </div><!--  end form-group --> 

   </div> <!-- end box booking -->

  <div class="clearfix"></div>

    <div id="success"></div>
    <button id="send_btn" type="submit" class="btn cpcbutton">Send Message</button>
    <p class="help-block"> <span class="glyphicon glyphicon-asterisk green"></span> Required Fields </p>
  </form>

Thanks in advance. 提前致谢。

Try this: 尝试这个:

$body = "";
foreach ($_POST as $Field=>$Value) { 
    if($Value != ''){
        $body .= "$Field: $Value\n\n";
    }
}

$to = 'info@zenwebcreative.com.au'; 
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details: $body";
$headers = "From: noreply@yourdomain.com\n";
$headers .= "Reply-To: $email_address"; 

mail($to,$email_subject,$email_body,$headers);
return true;            

I replaced all the code that assigns variables from the $_POST array to the snippet you provided. 我替换了所有将$ _POST数组中的变量分配给您提供的代码段的代码。 That basically do the same thing that your previous code was doing. 基本上,这和您先前的代码所做的相同。

Your foreach -loop is working as is, but the code looks a bit cleaner when using empty() instead, like this (but the one you have already does the same job!): 您的foreach -loop仍在按原样工作,但是使用empty()时,代码看起来更简洁一些(但是您已经做过的工作!):

foreach ($_POST as $field=>$value) { 
    if (!empty($value)) {
        $body .= "$field: $value\n\n";
    }
}

This assigns all the variables in the global $_POST -array that is not empty into the $body -variable. 这会将全局$_POST -array中不为空的所有变量分配到$body -variable中。 Using this, you don't need the other $_POST statements (for example $message = $_POST['message']; ). 使用此方法,您不需要其他$_POST语句(例如$message = $_POST['message']; )。 The only problem with this is that ALL your content from the $_POST -array is printed (even the submit-buttons value!). 唯一的问题是,将打印$_POST -array中的所有内容(甚至是commit-buttons值!)。

Then you just put that in your mail -function like this: 然后你只需把在你的mail功能全是这样的:

$email_body = "You have received a new message from your website contact form.\n\n";
$email_body .= "Here are the details:\n\n";
$email_body .= "$body";
mail($to, $email_subject, $email_body, $headers);

Another alternative is to check every field explicitly, although this will generate a lot more code. 另一个选择是显式检查每个字段,尽管这将生成更多代码。

if (!empty($_POST['name']))
    $body .= "Name: ".$_POST['name']."\n\n";
if (!empty($_POST['email']))
    $body .= "Email: ".$_POST['email']."\n\n";
if (!empty($_POST['phone']))
    $body .= "Phone: ".$_POST['phone']."\n\n";

Same deal here with how you can add it to your mail-function. 您可以将其添加到邮件功能的方法与此相同。

There are of course other ways of doing things, and out of the two, I'd recommend the foreach -loop, as it's much less and cleaner code, that should do the same job. 当然,还有其他处理方式,在这两种方式中,我建议使用foreach -loop,因为它更少而且更简洁的代码也可以完成相同的工作。 If it prints the "submit" values too, you can just add a piece of code that skips that element of the global $_POST array. 如果它也打印“提交”值,则只需添加一段代码即可跳过全局$_POST数组的该元素。


You should have a statement that prevents the script to be run every time someone visits this page directly, like having a if ($_POST['submit'] == 'submit') (where submit are the name and value of your submit-button in the HTML form) statement that wraps all your mail-relevant code. 您应该具有防止脚本每次有人直接访问该页面时运行,就像有一个声明if ($_POST['submit'] == 'submit')其中submit的名称和您呈交的价值HTML表单中的“按钮”)包装所有与邮件相关的代码。 This way, mails are only sent after the form is submitted. 这样,仅在提交表单后才发送邮件。

You should create a whitelist array of your accepted keys: 您应该创建一个包含接受密钥的白名单数组:

$whitelist = array('name', 'email', 'phone');

And then loop through the array as follows: 然后如下遍历数组:

foreach($whitelist as $key){
  if(isset($_POST[$key]) && $_POST[$key] != ''){
    $body .= ucfirst($key) . ": " . htmlspecialchars($_POST[$key], ENT_QUOTES) . "\n";
  }
}

foreach loops through the array, isset checks that the field is set, ucfirst makes the key look presentable in the email by capitalizing the first character, and htmlspecialchars with the ENT_QUOTES flag ensures the characters are properly converted for the email. foreach数组, isset检查是否设置了该字段, ucfirst通过大写第一个字符使键在电子邮件中看起来可显示,并且带有ENT_QUOTES标志的htmlspecialchars确保为电子邮件正确转换了字符。

You should always create a whitelist for this type of loop, not only for security purposes but also because you'll be looping through unnecessary or irrelevant keys, such as: 您应该始终为此循环类型创建白名单,这不仅出于安全目的,还因为您将遍历不必要或不相关的键,例如:

<button type="submit" name="submit" value="1">Submit</button>

Your email will then see: 然后,您的电子邮件将显示:

Submit: 1

Which makes no sense to the recipient. 这对接收者毫无意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM