Advertisement
gitlez

YA: Test For Form Inputs

Nov 2nd, 2011
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.55 KB | None | 0 0
  1. <?php
  2.  
  3. defined('METHOD')? null : define('METHOD',$_SERVER['REQUEST_METHOD']);
  4.  
  5. function requiredInputs(){
  6.     $a = func_get_args();
  7.     if(is_array($a[0])){ $a = $a[0];}
  8.     $c = func_num_args();
  9.     $r = Array('errors'=>false);
  10.     for($i=0;$i<$c;++$i){
  11.         if(!isset($_POST[$a[$i]])){
  12.             $r['missing'][] = $a[$i];
  13.             $r['errors'] = true;
  14.         }
  15.     }
  16.     return $r;
  17. }
  18.  
  19. $items = Array('item1','item2','item3','item4','item5');
  20.  
  21. if(METHOD === 'POST'){
  22.     echo '<pre>';
  23.     $check = requiredInputs('item1','item2','item3','item4','item5'); // Or requiredInputs($items); It can take a single array or a list of fields
  24.     if($check['errors'] === true){
  25.         echo 'The following were missing from the form input:' . PHP_EOL;
  26.         echo implode(PHP_EOL, $check['missing']) . PHP_EOL;
  27.     }else{
  28.         echo 'All Form Inputs were received.' . PHP_EOL;
  29.     }
  30.     echo PHP_EOL;
  31.     echo '$_POST = ';
  32.     print_r($_POST);
  33.     exit;
  34. }else{
  35.     // This just creates some random form fields to test.
  36.     $form = '';
  37.     foreach($items as $item){
  38.         if(rand(0,10) >= 5){
  39.             $value = (rand(0,10) >= 5)? 'someValue' : '';
  40.             $form .= '<input type="text" name="' . $item . '" value="' . $value . '"><br>' . PHP_EOL;
  41.         }else{
  42.             $form .= '<span>Missing: ' . $item . '</span><br>' . PHP_EOL;
  43.         }
  44.     }
  45. }
  46. ?>
  47. <html>
  48.     <head>
  49.     </head>
  50. <body>
  51.     <form method="post">
  52.         <?php echo $form; ?>
  53.         <input type="submit" value="Submit">
  54.     </form>
  55. </body>
  56. </html>
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement