Server side form field validation with PHP only

Almost for every submitted form you need a simple form check to test the required fields. Form field validation and error reporting becomes complicated if you have to handle more then three required fields. This function will do all this work: Validation of required fields and shows some user friendly errors. After submitting the form you get a message which fields are empty and the empty fields are in a different color.

The validation of your form is processed by PHP code only, it would be more user friendly if your web page will test the entries on the client side first!

PHP Snippet or function

session_start();
unset($_SESSION);
$req_fields = array("_name"=>"name", "timestamp"=>"your time", "field"=>"some field", "check"=>"checkbox");
$msg = " ";

function check_empty_fields($method = "post") {
    global $req_fields, $msg;
    $use_method = ($method == "post") ? $_POST : $_GET;
    $errors = "";
    $count_empty = 0;
    foreach ($req_fields as $key => $val) {
        $field_name = (array_key_exists($key, $req_fields)) ?  $req_fields[$key] : $key;
        if (!array_key_exists($key, $use_method) || empty($use_method[$key])) {
            $_SESSION[$key] = true;
            $errors .= "|".$field_name;
            $count_empty++;
        } else {
            $_SESSION[$key] = false;
        }
    }
    if ($count_empty == 0) {
        return true;
    } else {
        $msg = "The following (required) fields are empty:";
        $msg_parts = explode("|", ltrim($errors, "|"));
        $num_parts = count($msg_parts);
        $msg .= "<b>";
        for ($i = 0; $i < $num_parts; $i++) {
            $msg .= $msg_parts[$i];
            if ($i <= $num_parts - 2) {
                $msg .= ($i == $num_parts - 2) ? " & " : ", ";
            }
        }
        $msg .= "</b>\n";
        return false;
    }
}

Example usage:

if (isset($_POST['submit'])) {
    if (check_empty_fields()) {
        // process the form data
    }
}

If you like to color your form fields if the field is empty (session based), use the kind of code.

echo '<input type="text" name="fieldname"';
echo (isset($_POST['fieldname'])) ? ' value="'.$_POST['fieldname'].'"' : ' value=""';
if (!$_SESSION['fieldname']) echo ' class="invalid">';

You need to create a pseudo class with the name “invalid” in your CSS style sheet.
Try this working demo, where this server side validation script is used.