35

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...";
    }
}
76

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...";
}
8
  • 3
    Again, I recommend an isSet($_POST[$field]). This is a good solution, though. – Borealid Jul 6 '10 at 21:47
  • 9
    empty() checks for both existance, and non false-ish values (null, false, 0, empty string). – Harold1983- Jul 6 '10 at 21:48
  • 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 7: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 7 '16 at 10:15
  • 1
    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
3

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...
2
  • You also need an isSet, I think - otherwise you'll get an error if the value wasn't posted at all. – Borealid Jul 6 '10 at 21:45
  • 3
    empty() does the whole job, no need to call isset() it's redundant logic. – mickmackusa Jun 29 '18 at 3:09
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.

2
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
}
2
  • if you have an empty field submitted then the strlen() evaluates to 0 which is false in PHP. – Nahser Bakht Sep 18 '12 at 21:59
  • This is the better answer if the 0 value is meaningful – Umbert Apr 26 at 8:30
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
  }
0

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...
}
0

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;
}
0
foreach($_POST as $key=>$value)
{

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

}

5
  • 1
    I do not understand how does this answer the question? – Dharman Aug 13 '19 at 18:49
  • if empty any $_POST key handle it and give message – dılo sürücü Aug 13 '19 at 19:43
  • 1
    Handle what exactly? You are checking random values. The question is about validating mandatory input. – Dharman Aug 13 '19 at 19:44
  • @Dharman the question is about having all fields filled out, so I don't see how this solution should be completely wrong – Nico Haase Aug 14 '19 at 8:43
  • What if POST is empty? What if I do not submit any data? Your validation will accept it because the foreach loop will not be executed. – Dharman Aug 14 '19 at 8:44
-1

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

2
  • 2
    Awww, always a dangerous practice, because it may be possible to smuggle global variables into your script through $_POST. – Pekka Jul 6 '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 6 '10 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.