Skip to content Skip to sidebar Skip to footer

PHP Forms Submission With Blank Answers Removed - Stop Body Message From Submitting If Field Is Blank

short version of php I have a form with two parts to it. An applicant and co applicant. I am trying to get it so that if the co applicant fields are empty or not required the php

Solution 1:

You could make this a lot easier to maintain with a slight rework of your form field names. For example, this line in your script:

$body_message .= 'Reason for Leaving: '.$field_cur_reason_leaving."\r\n";

If you change this form field name to $reason_for_leaving in your HTML--and do the same for the other fields--you could process your form and generate your email message like this:

$body_message = ''; // initialize email body

foreach ( $_POST as $key => $value ) {
    if ($key == 'somethingspecial') {
        // special parsing for this field
    } else {
        // some basic sanitization
        $_POST[$key] = trim(stripcslashes(strip_tags( $value )));
        if ($_POST[$key] != '') {
            // If field isn't blank, make the form field name
            // look nice and add the value for the form field
            $body_message .= ucwords(str_ireplace( '_', ' ', $key )) .': '. $value . "\r\n";
        }
    }
}

Obviously, you'll need to do a little more work for special form fields (like your checkboxes), but this should greatly simplify your code (and your life).


Post a Comment for "PHP Forms Submission With Blank Answers Removed - Stop Body Message From Submitting If Field Is Blank"