Intenta con la función
filter_input_array().
Supongamos que tienes el siguiente formulario HTML:
<form method="post" action="<?= $_SERVER['PHP_SELF']; ?>">
<input type="text" name="email" /> <input type="text" name="sevendigits" /> <input type="text" name="zerototwenty" />
<input type="checkbox" name="checkboxes[]" value="cb1" /> <input type="checkbox" name="checkboxes[]" value="cb2" /> <input type="checkbox" name="checkboxes[]" value="cb3" />
<input type="hidden" name="validurl" value="http://elhacker.net" />
<input type="submit" value="Submit" />
Haciéndolo a la vieja usanza sería así:
$email = $_POST['email'];
$sevendigits = $_POST['sevendigits'];
$zerototwenty = $_POST['zerototwenty'];
// ... and so on.
// Empty email, show error or do something else.
return;
}
if(!empty($sevendigits)){ $sevendigits = intval($sevendigits); }
else {
// Not seven digits
}
}
else {
// Error, sevendigits wasn't submitted.
}
// ... and so on, you get the idea.
Y con la función filter_input_array():
<?php
// Works only in PHP 5.2.0 or later.
// This ensures that $_POST['email'] is actually a
// valid email address.
'email' => FILTER_VALIDATE_EMAIL,
// This filter verifies that $_POST['sevendigits'] is
// exactly a seven digit number using a regular expression.
'sevendigits' => array('filter' => FILTER_VALIDATE_REGEXP
, 'options' => array('regexp' => '/^\d{7}$/') ),
// Make sure that $_POST['zerototwenty'] is a number
// 0 to 20 using the min_range and max_range specs.
'zerototwenty' => array('filter' => FILTER_VALIDATE_INT
, 'options' => array('min_range' => 0, 'max_range' => 20)
),
// Verify that the incoming $_POST['checkboxes'] from
// the checkbox list is actual an array like we expect.
'checkboxes' => array('filter' => FILTER_VALIDATE_INT
, 'flags' => FILTER_REQUIRE_ARRAY,
),
// Make sure that the hidden URL field is a valid
// properly formatted URL.
'validurl' => FILTER_VALIDATE_URL,
// ----- A few other filter examples not included
// ----- in the <form> sample above. I just felt like
// ----- experimenting with a few other filters.
// This field must be a boolean type. If mustbeboolean is
// "true", "1", "TRUE" or some other value that represents
// true then this will be true. Otherwise, it will be false.
'mustbeboolean' => array('filter' => FILTER_VALIDATE_BOOLEAN
),
// Encode a URL that we need encoded from $_POST['encodeurl']
'encodeurl' => array('filter' => FILTER_SANITIZE_ENCODED
),
// This dosen't exist in the form, I'm just using it to show
// what the result will be when an input doesn't exist.
'doesnotexist' => FILTER_VALIDATE_INT
);
// Filter and sanitize the incoming $_POST[] with the filter above.
// Here's an example of checking if $_POST['email'] made it
// past our FILTER_VALIDATE_EMAIL filter.
if( empty($inputs['email']) ) { echo "Empty or invalid email entered.";
}
?>
Esta última función agrega una capa de seguridad/filtrado.