PHP

Function to Detect Empty Form Fields

This function allows the reader to loop through POST or GET fields checking to see if they are empty. I got the original version of this method from somewhere else, however, once again I cannot remember where. I have added a new check to make sure that users don’t try and hack your form by entering a space or 10 spaces or whatever. I am going to add more checks soon but this works for almost any form element except option boxes for some reason. Anyway here is the function:

$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(!empty($use_method[$key])){
        	$newString = str_replace(" ","",$use_method[$key]);
	        if(strlen($newString) <= 0){        
				$errors .= "|".$field_name;
			    $count_empty++;
	        }
        }elseif(!array_key_exists($key, $use_method) || empty($use_method[$key])){
        	$errors .= "|".$field_name;
		    $count_empty++;
        }
    }
	    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 .= "<br><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;
	    }
}

It’s actually strangely simple once you read through it, it just looks elitist because it uses variables derived from input. It first gets the form and then foreach’s each field to do a number of checks to ensure the field is not empty. After it has performed these checks it builds up a string of errors and prints it all back out to $msg. This variable can then be sent into your page and displayed. the typical usage of this would be:

if(check_empty_fields()){
     //do form actions
}else{
     echo $msg; //will echo something like "the following required fields are empty: country, name, town"
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s