注意:未定义索引:变量


Notice: Undefined index: variable

我试图建立以下形式:

<form method="post" action="Index.php">
  <label>Name </label>
  <input name="name" placeholder="Type Here"><br />
  </br>
  <label>Email </label>
  <input name="email" placeholder="Type Here">
  <br /></br>
  <label style="display:block;">I need some information regarding:</label>
  <textarea name="message" placeholder="Type Here"></textarea>
  <br />
  <label>*What is 2+2? (Anti-spam)</label>
  <input name="human" placeholder="Type Here">
  <br />
  <input id="submit" name="submit" type="submit" value="Submit" style="height:30px;">
</form>
PHP代码:
<?php
  $name = $_POST['name'];
  $email = $_POST['email'];
  $message = $_POST['message'];
  $from = 'From: TangledDemo';
  $to = 'hello@emailaddress.com';
  $subject = 'Hello';
  $human = $_POST['human'];
  $body = "From: $name'n E-Mail: $email'n Message:'n $message";
  if ($_POST['submit'] && $human == '4') {
    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>';
    }
  } else if ($_POST['submit'] && $human != '4') {
    echo '<p>You answered the anti-spam question incorrectly!</p>';
  }
  if ($_POST['submit']) {
    if ($name != '' && $email != '') {
      if ($human == '4') {
        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>';
        }
      } else if ($_POST['submit'] && $human != '4') {
        echo '<p>You answered the anti-spam question incorrectly!</p>';
      }
    } else {
      echo '<p>You need to fill in all required fields!!</p>';
    }
  }
?>

但是总是出现这些错误:

注意:未定义的索引:名称在C:'xampp'htdocs'bet4info' index .php on19行

注意:未定义的索引:电子邮件在C:'xampp'htdocs'bet4info' index .php第20行

注意:未定义的索引:消息在C:'xampp'htdocs'bet4info' index .php第21行

注意:未定义的索引:人类在C:'xampp'htdocs'bet4info' index .php第25行

注意:未定义的索引:提交在C:'xampp'htdocs'bet4info' index .php第29行

注意:未定义的索引:提交在C:'xampp'htdocs'bet4info' index .php第35行

注意:未定义的索引:提交在C:'xampp'htdocs'bet4info' index .php第38行

为什么会这样?

代替

$name = $_POST['name'];
if ($_POST['submit'] && $human == '4') {   
使用

$name = isset($_POST['name']) ? $_POST['name'] : '';
if (isset($_POST['submit']) && $human == '4') {   

首先,您必须使用isset函数进行检查:

if(isset($_POST['name']) && isset($_POST['email']) &&....)
{
    // If isset then assign data to variable $name = $_POST['name'],...
}
else
{
    // Redirect to the error page
}

就像这样,所有的变量都是一样的