42

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...";
    }
}
Taryn
  • 242,637
  • 56
  • 362
  • 405
FFish
  • 10,964
  • 34
  • 95
  • 136

10 Answers10

82

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-
  • 3,329
  • 2
  • 23
  • 22
  • 3
    Again, I recommend an isSet($_POST[$field]). This is a good solution, though. – Borealid Jul 06 '10 at 21:47
  • 9
    empty() checks for both existance, and non false-ish values (null, false, 0, empty string). – Harold1983- Jul 06 '10 at 21:48
  • Almost the same as my approach. However I'm stuck with the "Proceed" part. You assumed that everything is required, so it's all go or no go. But what if some aren't. Do I have to check once again for each and every $_POST if they are empty so I can sql them to database? I feel bad loop checking for all $_POST twice. Or is that just how it usually is? A newbie here...help please? – Fred Nov 08 '12 at 14:49
  • or instead of the $required array, u can directly use `foreach($_POST as $field => $ignore_value)` – Osa Apr 16 '13 at 22:33
  • 2
    This `foreach` will only validate the last value of `array` (which is email) as it overrides the previous `$error` validation. – Nimitz E. Aug 28 '15 at 07:58
  • 7
    @NimitzE. not necessarily. `$error` is set to false, and only when a field is empty is it changed. It doesn't matter which field throws it, because once its thrown, its thrown. i.e. if `name` was empty, it would run `false, false, false, true, false, false` but as there's no `else` in the `if`, `$error` is now `true`. – MLMLTL Apr 07 '16 at 10:15
  • 2
    Just be careful if 0 is an acceptable value for a required field. As @Harold1983- mentioned, these are treated as empty in PHP. Better to use isset – accord_guy Nov 28 '17 at 20:55
  • Right said by @NimitzE.better declare an empty array for `$errors = array()` and use `array_push()` function and check for `empty($errors)`. if `$errors` array is empty then it means loop processing was successful. – Muhammad Tarique Nov 16 '19 at 09:08
5
if( isset( $_POST['login'] ) &&  strlen( $_POST['login'] ))
{
  // valid $_POST['login'] is set and its value is greater than zero
}
else
{
  //error either $_POST['login'] is not set or $_POST['login'] is empty form field
}
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
Nahser Bakht
  • 920
  • 2
  • 13
  • 27
3

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
  • 53,861
  • 28
  • 137
  • 147
2

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
  • 161,348
  • 33
  • 346
  • 320
1
if (array_filter(["param1", "param2", "param3"],
    fn(string $param) => !array_key_exists($param, $_POST))) {
        throw new Exception('Missing element');
}
0

I did it like this:

$missing = array();
 foreach ($_POST as $key => $value) { if ($value == "") { array_push($missing, $key);}}
 if (count($missing) > 0) {
  echo "Required fields found empty: ";
  foreach ($missing as $k => $v) { echo $v." ";}
  } else {
  unset($missing);
  // do your stuff here with the $_POST
  }
Calin Rusu
  • 49
  • 3
-1

I just wrote a quick function to do this. I needed it to handle many forms so I made it so it will accept a string separated by ','.

//function to make sure that all of the required fields of a post are sent. Returns True for error and False for NO error  
//accepts a string that is then parsed by "," into an array. The array is then checked for empty values.
function errorPOSTEmpty($stringOfFields) {
        $error = false;
            if(!empty($stringOfFields)) {
                // Required field names
                $required = explode(',',$stringOfFields);
                // Loop over field names
                foreach($required as $field) {
                  // Make sure each one exists and is not empty
                  if (empty($_POST[$field])) {
                    $error = true;
                    // No need to continue loop if 1 is found.
                    break;
                  }
                }
            }
    return $error;
}

So you can enter this function in your code, and handle errors on a per page basis.

$postError = errorPOSTEmpty('login,password,confirm,name,phone,email');

if ($postError === true) {
  ...error code...
} else {
  ...vars set goto POSTing code...
}
user1518699
  • 385
  • 2
  • 8
  • 20
-1

Note : Just be careful if 0 is an acceptable value for a required field. As @Harold1983- mentioned, these are treated as empty in PHP. For these kind of things we should use isset instead of empty.

$requestArr =  $_POST['data']// Requested data 
$requiredFields = ['emailType', 'emailSubtype'];
$missigFields = $this->checkRequiredFields($requiredFields, $requestArr);

if ($missigFields) {
    $errorMsg = 'Following parmeters are mandatory: ' . $missigFields;
    return $errorMsg;
}

// Function  to check whether the required params is exists in the array or not.
private function checkRequiredFields($requiredFields, $requestArr) {
    $missigFields = [];
    // Loop over the required fields and check whether the value is exist or not in the request params.
    foreach ($requiredFields as $field) {`enter code here`
        if (empty($requestArr[$field])) {
            array_push($missigFields, $field);
        }
    }
    $missigFields = implode(', ', $missigFields);
    return $missigFields;
}
-1
foreach($_POST as $key=>$value)
{

   if(empty(trim($value))
        echo "$key input required of value ";

}

dılo sürücü
  • 3,821
  • 1
  • 26
  • 28
-2

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

Doug Molineux
  • 12,283
  • 25
  • 92
  • 144
  • 2
    Awww, always a dangerous practice, because it may be possible to smuggle global variables into your script through `$_POST`. – Pekka Jul 06 '10 at 21:48
  • I've heard something about this before, and its probably not the best way to go :) especially if its something important – Doug Molineux Jul 06 '10 at 21:56