2

Possible Duplicate:
More concise way to check to see if an array contains only numbers (integers)
PHP checking if empty fields

I have form that submits 10 fields, and 7 of them should be filled, here is how i chek it now in PHP:

if (!$name || !$phone || !$email || !$mobile || !$email || !$state || !$street || !  $city) {
        echo '<div class="empty_p">You have empty fields!!!</div>';}
else{
        //process order or do something
}

My question is: is there more simple way to do this? Because sometimes I have even more strings to check (12-15)

Community
  • 1
  • 1
SomeoneS
  • 1,207
  • 2
  • 19
  • 34

7 Answers7

5

Another possibility:

$elements = array($name, $email, $mobile);
$valid = true;

foreach ($elements as $element) {
    if (empty($element)) {
        $valid = false;
    }
}

if ($valid) {
    // complete
} else {
    // alert! some element is empty
}
Linus Unnebäck
  • 23,234
  • 15
  • 74
  • 89
Sem
  • 4,477
  • 4
  • 33
  • 52
3

Something like this?

foreach($_POST as $key => $value) 
{
    if (empty($_POST[$key]))
    {
        echo '<div class="empty_p">'.$_POST[$key].' is empty.</div>';
    }
}
Bono
  • 4,757
  • 6
  • 48
  • 77
2

It's good to be specific about where this data should be expected, e.g. $_POST:

if (!isset($_POST['name'], $_POST['phone'], $_POST['email'], $_POST['mobile'], $_POST['state'], $_POST['street'], $_POST['city'])) {
    // something is up
}

You can shorten this code a little bit by creating an array with your required field names:

$required_fields = array('name', 'phone', 'email', 'mobile', 'state', 'street', 'city');

The 'check-for-existence' code can then be simplified to:

foreach ($required_fields as $f) {
    if (!isset($_POST[$f])) {
        // something is up
    }
}

The better way ™

However, you should seriously consider combining both existence and validation / sanitization checks. PHP provides a family of filter functions functions that you can use to validate and/or sanitize your input variables. For example, to get equivalent behavior as above:

$required_fields = filter_input_array(INPUT_POST, array(
    'name' => FILTER_UNSAFE_RAW,
    'email' => FILTER_VALIDATE_EMAIL,
));

if (is_null($required_fields) || in_array(null, $required_fields, true)) {
    // some fields are missing
}

Fields that exist but fail validation will be set to false, so this is how you detect such an event:

foreach ($required_fields as $name => $value) {
    if (false === $value) {
        // field $name failed validation (e.g. bad email format)
    } elseif (!strlen(trim($value))) {
        // field is empty
    }
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

You can write Foreach loop

  foreach($_POST as $key => $value) 
    {
        if (!isset($_POST[$key]) || empty($_POST[$key])
        {
            echo '<div class="something">You have empty fields!!!</div>';
        }
    }
Adam Bremen
  • 685
  • 1
  • 7
  • 18
1

The best way would be to create some sort of form validator. However you can use this function:

<?php
    function isAnyEmpty() {
        $total = 0;
        $args = func_get_args();
        foreach($args as $arg)
        {
            if(empty($arg)) {
                return true;
            }
        }

        return false;
    }
    $var1 = 1;
    $var2 = 'test';
    $var3 = '';

    if(isAnyEmpty($var1, $var2, $var3)) {
        echo 'empty fields!';
    }
?>
Zbigniew
  • 27,184
  • 6
  • 59
  • 66
1

You could try creating a general validation class that could be reused and be more precise.

Some pseudo code:

<?

class validateFields {
    $validators = array(
        "name" => array(
            "empty" => array(
                "rule"          => "some regex",
                "errorMessage"  => "name may not be empty"
            ),
            "noNumbers" => array(
                "rule"          => "some regex",
                "errorMessage"  => "No numbers are allowed in the name field"
            )
        ),
        "otherVariable" => array(
            "atLeast50chars" => array(
                "rule"          => "some regex",
                "errorMessage"  => "This field must be at least 50 chars"
            )
        )
    );


    public function Validate($post){
        $errors = array();

        foreach($_POST as $key => $value){
            if(!array_key_exists($key, $validators)) {
                continue;
            }

            foreach($validators[$key] as $validator) {
                if(!preg_match($validator["rule"], $value) {
                    $errors[$key] = $validator["errorMessage"];
                    break;
                }
            }
        }

        return $errors;
    }
}


?>

Then in your code you could do something like:

$errors = Validate($_POST);
foreach($error as $errorMessage) {
    echo $errorMessage . "</br>";
}

Of course you could fancy this up, adding divs with classes right below/beside the concerning input field and load the $errorMessage into there. I'm sure there's loads of examples out there :)

Deruijter
  • 2,077
  • 16
  • 27
-1
<input type="text" name="required[first_name]" />
<input type="text" name="required[last_name]" />
...


$required = $_POST['required'];
foreach ($required as $req) {
   $req = trim($req);
   if (empty($req))
      echo 'gotcha!';
}

/* update */

OK! guys, easy...

You can make it more secure, just with type casting as all we programmers do for out coming data, like $id = (int) $_GET['id'], like $username = (string) addslashes($_POST['username']) and so on...;

$required = (array) $_POST['required'];

And then, what ever comes from post fields let them come, this code just seek what it need. That is it! Uhh...

Kerem
  • 11,377
  • 5
  • 59
  • 58
  • beautiful. Never would have thought of that..well you learn something every day! – Steve Jun 08 '12 at 14:19
  • It's a bit late, that's why the imagination is running low here :P – Steve Jun 08 '12 at 14:40
  • Umm, this works great, but what if someone edit source code of form and change "required[first_name]" to nothing. Then nothing will be sent, and there will be missing data? – SomeoneS Jun 08 '12 at 20:01
  • 4
    This is a horrible idea. A client modifying the HTML or simply sending a manually crafted POST request will be able to circumvent this check. While this will most likely not cause serious issues it's pretty ugly. – ThiefMaster Jun 08 '12 at 20:23
  • 6
    Security magically through `addslashes` and that already in the edit you did to focus on security. Ouch, that's horrorful. Also as ThiefMaster wrote, you don't whitelist the input variable names. That is so discusting. You get a -1 from me. – hakre Jun 09 '12 at 12:48
  • And that bad that it turns out into a chain of questions. Next step of the ping-pong style (yeah it's the TS as well): [Preventing form empty submit](http://stackoverflow.com/q/10955464/367456) – hakre Jun 09 '12 at 15:31