You want to make sure a value has been supplied for a form element. For example, you want to make sure a text box hasn't been left blank.
Use strlen( ) to test the element in $_GET or $_POST, as in Example 9-4.
Testing a required field
Different types of form elements cause different types of behavior in $_GET and $_POST when left empty. Blank text boxes, text areas, and file-upload boxes result in elements whose value is a zero-length string. Unchecked checkboxes and radio buttons don't produce any elements in $_GET or $_POST. Browsers generally force a selection in a drop-down menu that only allows one choice, but drop-down menus that allow multiple choices and have no choices selected act like checkboxes'they don't produce any elements in $_GET or $_POST.
What's worse, requests don't have to come from web browsers. Your PHP program may receive a request from another program, a curious hacker constructing requests by hand, or a malicious attacker building requests in an attempt to find holes in your system. To make your code as robust as possible, always check that a particular element exists in $_GET or $_POST before applying other validation strategies to the element. Additionally, if the validation strategy assumes that the element is an array of values (as in Example 9-15), ensure that the value really is an array by using is_array( ).
Example 9-5 uses isset( ), strlen( ), and is_array( ) for maximally strict form validation.
Strict form validation
In a moment of weakness, you may be tempted to use empty( ) instead of strlen( ) to test if a value has been entered in a text box. Succumbing to such weakness leads to problems since the one character string 0 is false according to the rules of PHP's boolean calculations. That means if someone types 0 into the children text box, causing $_POST['children'] to contain 0, empty($_POST['children']) is TRue'which, from a form validation perspective, is wrong.
9.2.4. See Also
Recipe 9.5 for information about validating drop-down menus, Recipe 9.6 for information about validating radio buttons, and Recipe 9.7 for information about validating checkboxes.