views:

47

answers:

5

Is there a simpler function to something like this:

if (isset($_POST['Submit'])) {
    if ($_POST['login'] == "" || $_POST['password'] == "" || $_POST['confirm'] == "" || $_POST['name'] == "" || $_POST['phone'] == "" || $_POST['email'] == "") {
        echo "error: all fields are required";
    } else {
        echo "proceed...";
    }
}
+1  A: 

empty and isset should do it.

if(!isset($_POST['submit'])) exit();

$vars = array('login', 'password','confirm', 'name', 'email', 'phone');
$verified = TRUE;
foreach($vars as $v) {
   if(!isset($_POST[$v]) || empty($_POST[$v])) {
      $verified = FALSE;
   }
}
if(!$verified) {
  //error here...
  exit();
}
//process here...
Jacob Relkin
You also need an isSet, I think - otherwise you'll get an error if the value wasn't posted at all.
Borealid
A: 

Personally I extract the POST array and then have if(!$login || !$password) then echo fill out the form :)

Pete Herbert Penito
Awww, always a dangerous practice, because it may be possible to smuggle global variables into your script through `$_POST`.
Pekka
I've heard something about this before, and its probably not the best way to go :) especially if its something important
Pete Herbert Penito
+4  A: 

Something like this:

// Required field names
$required = array('login', 'password', 'confirm', 'name', 'phone', 'email');

// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field) {
  if (empty($_POST[$field])) {
    $error = true;
  }
}

if ($error) {
  echo "All fields are required.";
} else {
  echo "Proceed...";
}
Harold1983-
Again, I recommend an isSet($_POST[$field]). This is a good solution, though.
Borealid
Thanks Harold, that was what I was looking for..
FFish
empty() checks for both existance, and non false-ish values (null, false, 0, empty string).
Harold1983-
A: 

I use my own custom function...

public function areNull() {
    if (func_num_args() == 0) return false;
    $arguments = func_get_args();
    foreach ($arguments as $argument):
        if (is_null($argument)) return true;
    endforeach;
    return false;
}
$var = areNull("username", "password", "etc");

I'm sure it can easily be changed for you scenario. Basically it returns true if any of the values are NULL, so you could change it to empty or whatever.

animuson
A: 

I think it's much better to use javascript to test if any fields are empty, and only after that to send the data for processing.

Pro's: less load for the server, as the testing is running on the client machine.

And I don't think there is an easier way to do it in php.

Victor Z.
Whether you validate input fields using client-side javascript or not, you should still always validate server-side as well
Mark Baker
yep, PHP check is just backing up my JS.
FFish