title: Basic form validation mechanism PHP
body: <p>I'm trying to set up simple example for form validation, whether field is empty or not. If field is not empty action redirect me to page ok.php and if not back to formvalidation.php. and change css of the field. I have problem with returning error array back to formvalidation.php and testing it to change css for input field. What am I doing wrong?</p>
  
  <p>formvalidation.php </p>
  
  <pre><code>&lt;?php require("includes/functions.php"); ?&gt;
  &lt;?php   
      global $errors;
  ?&gt;
  
  &lt;form action="posting.php" method="p"&gt;
      &lt;ul&gt;
          &lt;li id="field"&gt;
              &lt;label for="field"&gt;Contact person &lt;/label&gt;
              &lt;input 
              &lt;?php
              if (empty($errors)) {
                  echo "style=\"background-color:   #ECECEC;\"";
              } else {
                  if (in_array("field", $errors)) {
                      echo "style=\"background-color: red;\"";}
                  } else {
                      echo "style=\"background-color:       #ECECEC;\"";
                  }
              }
              ?&gt; 
              type="text" name="field"/&gt;
          &lt;/li&gt;
          &lt;li&gt;
              &lt;input id="saveForm" class="button_text" type="submit"  name="submit" value="Submit" /&gt;
          &lt;/li&gt;
      &lt;/ul&gt;
  &lt;/form&gt;  
  </code></pre>
  
  <p>action.php</p>
  
  <pre><code>&lt;?php require("includes/functions.php"); ?&gt;
  &lt;?php
      $errors = form_validation ();
  
      if (!empty($errors)) {
          redirect_to("formvalidation.php");
      } else {
          redirect_to("ok.php");
      }
  ?&gt;
  </code></pre>
  
  <p>function</p>
  
  <pre><code>&lt;?php
  function form_validation () {
  
      $errors = array ();
  
      $required_fields = array('field');
      foreach($required_fields as $fieldname) {
          if (!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) {
              $errors[] = $fieldname;
          }
      }
  
      return $errors;
  
  }
  </code></pre>