0

I'm new to PHP and struggling getting a form started. I'm getting the following error - Notice: Undefined index: email in C:\xampp\htdocs\Matt\login.php on line 7

Do I need to declare empty vars before code. My code;

<?php
  if (array_key_exists("submit", $_POST)) {
    print_r($_POST);
  }

  if (!$_POST['email']) {
      $error .= "An Email is required<br>";
  }
  if ($error != "") {
    $error = "<p>There were error(s) in your form:</p>".$error;
  }
?>

<div class="error"><?php echo $error; ?></div>
<form method="post" id="logInForm">
  <input type="email" class="form-control" name="email" id="email" placeholder="email">
  <input type="password" class="form-control" name="password" id="password" placeholder="password">
  <div class="checkbox pt-2">
    <label>
      <input type="checkbox" name="stayLoggedIn" value="1"> Stay Logged In
    </label>
  </div>
  <input type="submit" name="submit" class="btn btn-primary btn-block mb-4" value="Log in!">
</form>
oversoon
  • 350
  • 2
  • 7
  • 21

1 Answers1

2

The $_POST['email'] variable doesn't exist. You can check for it using isset($_POST['email']) and then use the value only if it exists. In your cause just using isset is enough.

if(!isset($_POST['email'])) {
   $error .= "A password is required<br>";
}
Steve
  • 1,903
  • 5
  • 22
  • 30
  • You missed a ')' in your answer. It solved one error but I get this error as well Notice: Undefined variable: error in C:\xampp\htdocs\Matt\login.php on line 7 – oversoon Sep 07 '18 at 23:31
  • fixed the mistake. If the isset code isn't entered then $error doesn't exist. – Steve Sep 07 '18 at 23:54