title: PHP Contact Form Best Practice: Input Validation not working
body: <p>My form input validation is not working as I expect it to work.    </p>
  
  <pre><code>&lt;?php
  $name = $_POST['name'];
  $email = $_POST['email'];
  $message = $_POST['message'];
  $from = 'From: Kontaktformular'; 
  $to = 'meine@mail.de'; 
  $subject = 'Kontaktformular';
  
  $body = "From: $name\n E-Mail: $email\n Message:\n $message";
  </code></pre>
  
  <p>In this Part I try to validate the input:</p>
  
  <pre><code>$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
  
  if ($email === FALSE) {
      echo 'Invalid email';
      exit(1);
  }
  
  $body = str_replace("\n.", "\n..", $body);
  </code></pre>
  
  <p>Now I try to send the mail if the input is not NULL:</p>
  
  <pre><code>if(isset($_POST['Submit'])) {
      if (mail ($to, $subject, $body, $from)) {
      echo '&lt;p&gt;Message was sent!&lt;/p&gt;';
      } else {
      echo '&lt;p&gt;Something went wrong :( Please try again&lt;/p&gt;';
      }
  } else {
      die ("Direct access not allowed!");
  }
  ?&gt;
  </code></pre>
  
  <p>My Problem is, that my the code returns either "Invalid email" or "Direct access not allowed!", but I am not sure what I am doing wrong.</p>
  
  <p>My HTML form:</p>
  
  <pre><code>&lt;form method="post" action="php-contact.php" class="animated fadeIn"&gt;
  &lt;label&gt;Name&lt;/label&gt;
  &lt;input name="name" placeholder="Name"&gt;
  
  &lt;label&gt;E-Mail&lt;/label&gt;
  &lt;input name="email" type="email" placeholder="E-Mail, zum antworten&amp;hellip;"&gt;
  
  &lt;label&gt;Nachricht&lt;/label&gt;
  &lt;textarea name="message" placeholder="Nachricht&amp;hellip;"&gt;&lt;/textarea&gt;
  
  &lt;input id="submit" name="submit" type="submit" value="Absenden"&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>I tried to use these code examples:
  <a href="https://stackoverflow.com/questions/11952473/proper-prevention-of-mail-injection-in-php">Proper prevention of mail injection in PHP</a></p>