使一个简单的联系框与HTML5和php工作正确


Making a simple contact box with HTML5 and php work correctly

我有一个关于使这两段代码一起工作的问题。我已经经历了几天努力找到为什么这会产生一个空白的页面,指向contact.php,而不是发送带有数据的电子邮件。简单的名称,企业名称和电子邮件。我不是一个php程序员,我会很感激的帮助,或者如果有人可以引导我在正确的方向。

HTML5示例

<form method="post" action="contact.php">
    <fieldset>
        <label for="alerts-name">Your Name</label> 
        <input type="text" name="name" id="alerts-name"  class="input" maxlength="30">
        </fieldset>
        <fieldset>
          <label for="alerts-business">Business Name</label> 
          <input type="text" name="business" id="alerts-business" class="input" maxlength="50">
        </fieldset>
        <fieldset>
          <label for="alerts-email">Your email</label> 
          <input type="text" name="email" id="alerts-email" class="input" maxlength="30">
        </fieldset>
        <label>*What is 2+2? (Anti-spam)</label><br />
        <input name="human" placeholder="Type Here">
        <fieldset>
        <br />
        <fieldset>
          <input type="submit" value="submit">
        </fieldset>
      </form>

下面是我使用的php代码。

<?php
  $name = $_POST['name'];
  $business = $_POST['business'];
  $email = $_POST['email'];
  $from = 'From: The Web Site';
  $to = 'myemail@site.com';
  $subject = 'Hello';
  $human = $_POST['human'];
  $body = "From: $name'n business: $business'n email:'n $email";
  if ($_POST['submit'] && $human == '4') {
  if (mail ($to, $name, $business, $email) ) {
  echo '<p>Your message has been sent!</p>';
  } else {
  echo '<p>Something went wrong, go back and try again!</p>';
  }
  } else if ($_POST['submit'] && $human != '4') {
  echo '<p>You answered the anti-spam question incorrectly!</p>';
  }
  ?>

你能确认这是你在"contact.php"文件中的PHP代码吗?还是所有这些都在同一个文件中?

你没有在PHP中使用$subject变量。你的"human"元素应该在HTML中也有一个type="text"(或者type="number")属性。

我有更多的成功与PHPMailer扩展时,执行任务与电子邮件,你可以从github获得最新的版本。那里有一个很好的用法示例,可以让你开始使用。

此外,作为题外话,当你在HTML5中编码时,你可以安全地使用新的"email"类型的输入,它有一些很好的内置验证:
 <input type="email" name="email" id="alerts-email" class="input" maxlength="30">

首先你的'from'头格式不正确-这应该是:

'From: The Website <the@website.com>'; or应该被省略,因为这是mail()函数的可选参数。

然后将四个参数传递给mail()函数- to, name, business和email。PHP文档中列出了相应的参数,它们是:

mail (string $to, string $subject, string $message[, string $additional_headers[, string $additional_parameters]]);

在这种意义上,你的函数应该读起来更像:

mail($to, $subject, $email);

tl;博士:

你使用$business作为你的邮件功能的一部分,你应该包括消息,这意味着你的电子邮件正文被解释为电子邮件的标题,是完全错误的格式