HTML表单的PHP代码应该放在哪里


Where should I put PHP code for a HTML form?

我似乎找不到这个特定问题的答案,所以如果它已经被回答了,我很抱歉,我还没有看到。

我有一个HTML表单,其中包含访问者姓名、电子邮件和消息;当然是用CSS设计的。我已经准备好了PHP代码,但我不确定该把它放在哪里。目前我把它放进了自己的页面上,html用"action"指向它,但当我测试页面并提交表单时,它只会进入一个空白页面。这是我的HTML代码示例。。和PHP代码。。。页面可以在这里看到。。。http://wayhigh.we.bs/contact.html

<form method="post" action="index.php" class="form" id="form1">
  <p class="name">
    <input name="name" type="text"            class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Name"  id="name" />
  </p>
  <p class="email">
    <input name="email" type="text" class="validate[required,custom[email]] feedback- input" id="email" placeholder="Email" />
  </p>
  <p class="text">
    <textarea name="text" class="validate[required,length[6,300]] feedback-input" id="comment" placeholder="Comment"></textarea>
  </p>

  <div class="submit">
    <input type="submit" value="SEND" id="button-blue"/>
    <div class="ease"></div>
  </div>
</form>

和PHP。。。

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['text'];
$from = 'From: J. Michaels'; 
$to = 'mailto:benjamminredden@gmail.com'; 
$subject = 'Hello from a visitor';
$body = "From: $name'n E-Mail: $email'n Message:'n $message";
if ($_POST['submit']) {
/* Anything that goes in here is only performed if the form is submitted */
}
if ($_POST['submit']) {
if (mail ($to, $subject, $body, $from)) { 
    echo '<p>Your message has been sent!</p>';
} else { 
    echo '<p>Something went wrong, go back and try again!</p>'; 
}
}
?>

您需要将name="submit"添加到提交按钮:

<input type="submit" name="submit" value="SEND" id="button-blue"/>

否则,if ($_POST['submit'])不会成功。

注意,我在if (isset($_POST['submit'])) 中添加了isset

PHPHTML表单之前的代码

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['text'];
$from = 'From: J. Michaels'; 
$to = 'mailto:benjamminredden@gmail.com'; 
$subject = 'Hello from a visitor';
$body = "From: $name'n E-Mail: $email'n Message:'n $message";
if (isset($_POST['submit'])) {
/* Anything that goes in here is only performed if the form is submitted */
}
if (isset($_POST['submit'])) {
if (mail ($to, $subject, $body, $from)) { 
    echo '<p>Your message has been sent!</p>';
} else { 
    echo '<p>Something went wrong, go back and try again!</p>'; 
}
}
?>
<form method="post" action="index.php" class="form" id="form1">
  <p class="name">
    <input name="name" type="text"            class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Name"  id="name" />
  </p>
  <p class="email">
    <input name="email" type="text" class="validate[required,custom[email]] feedback- input" id="email" placeholder="Email" />
  </p>
  <p class="text">
    <textarea name="text" class="validate[required,length[6,300]] feedback-input" id="comment" placeholder="Comment"></textarea>
  </p>

  <div class="submit">
    <input type="submit" value="SEND" id="button-blue"  name="submit" />
    <div class="ease"></div>
  </div>
</form>