Check entire $ _POST variable at once

instead of checking all my variable messages from the form one at a time, is there a way to run one check to make sure they are not empty, something like

if(!isset(ALL $_POST)){ echo "one of your fields is not completed."; } 
+2
source share
3 answers

You can create an array of required fields and pass through it

 $required_fields = array("name", "address", "phone", "email"); foreach ($require_fields as $field) { if (!strlen($_POST[$field])) { echo "$field cannot be empty"; } } 
+9
source

No , because how does your program know what should exist?

However, if you have a list of fields that are expected, you can easily write a function to check. I called it array_keys_exist because it does the same thing as array_key_exists , with the exception of a few keys:

 function array_keys_exist($keys, $array) { foreach ($keys as $key) { if (!array_key_exists($key, $array)) return false; } return true; } $expectedFields = array('name', 'email'); $success = array_keys_exist($expectedFields, $_POST); 
+1
source

It is impossible to do as you think (since PHP does not know what values ​​should be).

But you could do this:

 <?php $POSTvaluesToCheck = array('write', 'here', 'all', 'the', 'values', 'that', 'are', 'mandatory', 'to', 'exist'); foreach($POSTvaluesToCheck as $key) { if(!isset($_POST[$key]) { echo $key . ' not set correctly!'; } } ?> 
0
source

Source: https://habr.com/ru/post/1208941/


All Articles