I have a PHP script that receives POST with multiple data (+30), all of them required. Instead of checking one by one with isset() and strlen(), as suggested here, would be great if I could catch the notice error "Undefined index" somehow. Researching on Google I found few old posts about this subject, like this one, so maybe there is some new technique or workaround to archive this goal.
UPDATE:
Based on @bishop answer, here is my solution:
try {
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$flds = ['data1', 'data2', 'data3'];
if (count(array_diff($flds, array_keys($_POST))) > 0) {
throw new Exception('Missing fields detected!');
}
/* @bishop solution
$vals = array_filter($_POST, function($val) { return ($val != ''); });
if (count(array_diff($_POST, $vals)) > 0) {
throw new Exception('Empty fields detected!');
}
*/
// I prefered using the bellow approach instead of @bishop
// solution, once I will need to sanitize values anyway
foreach($_POST as $input => $value) {
$_POST[$input] = trim($value);
if (strlen($_POST[$input]) === 0) {
throw new Exception('Empty fields detected!');
}
//$_POST[$input] = mysqli_real_escape_string($conn, $value);
}
}
} catch (Exception $e) {
echo $e->getMessage();
}