Generic $_GET validator
I want a dead simple generic $_GET-vars validator, and don't have any desire to reinvent the wheel.
Is there any solid and simple script I can use, something like:
function secure($varName,$format = 'int') {
//format: boolean,int,dec,str,date
//add stripslashes if mq
$var = $_GET[$varNa开发者_如何转开发me];
switch($format) {
case 'int':
$r = floor($var);
break;
case 'boolean':
$r = ($var === true);
break;
case 'dec':
$r = preg_replace("/0-9.-/i", "", $val);
break;
case 'str':
..
case 'date':
//ISO 8601 is enough...
}
regards, //t
filter_input()
comes fairly close to what you want to do.
It's got a decent number of validation and sanitation filters.
An example stolen from the manual:
<?php
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL,
FILTER_FLAG_PATH_REQUIRED));
?>
Pekka gave a great function I didn't know about, but filter_input_array
is what you actually want.
http://www.php.net/manual/en/function.filter-input-array.php
Example:
Edit: Now shows how to validate a DateTime (ie, a timestamp).
/* data that came from GET
$_GET = array(
'id' => '14',
'name' => 'Guidoe'
'archived' => 'on',
'date' => '2006-12-12 10:00:00'
);
*/
$args = array(
'id' => array('filter' => FILTER_VALIDATE_INT,
'options' => array('min_range' => 1, 'max_range' => 1000)
),
'archived' => array('filter' => FILTER_VALIDATE_BOOLEAN,
'flags' => FILTER_NULL_ON_FAILURE
),
'date' => array('filter' => FILTER_CALLBACK,
'options' => 'valid_date_time'
)
'name' =>array('filter'=>FILTER_SANITIZE_STRING,
'flags'=>FILTER_FLAG_ENCODE_HIGH
)
);
function valid_date_time($string) {
$parsed = date_parse($string);
if($parsed['error_count']>0 || $parsed['warning_count']>0)
return false;
return new DateTime($string);
}
$myinputs = filter_input_array(INPUT_GET, $args);
精彩评论