title: php: best way to validate POST
body: <p>I have been using the code below to validate my user input by $_POST:</p>
  
  <pre><code>if(isset($_POST['name']) &amp;&amp; !empty($_POST['name'])) {
      $n=$_POST['name'];
  }
  else {
      $errors[] = "Please give a name";
  }
  </code></pre>
  
  <p>This code checks whether 'name' was actually set, which is obvious and clear and needed.
  Secondly, it checks whether user typed something in textfield to give a value for name.
  However, if user gives SPACE " " as input it accepts it because it is not empty it has SPACE.</p>
  
  <p>I found one way of doing it right:</p>
  
  <pre><code>if(isset($_POST['name'])) {
      $n = trim($_POST['name']);
      if(empty($n)) {
          $errors[] = "Please give a name";
      }
  }
  
  else {
  $errors[] = "Please give a name";
  }
  </code></pre>
  
  <p>But here I am repeating same error message twice, so how can it be optimized?</p>