define('VRFY_RE', 1);
define('VRFY_FUNC', 2);
...
function verify($specs, $dfltSpec = null) {
$fail = array();
foreach ($_REQUEST as $name => $val) {
if (isset($specs[$name])) {
$spec = $specs[$name];
} elseif (is_null($dfltSpec)) {
continue;
} else {
$spec = $dfltSpec;
}
switch ($spec['type']) {
case VRFY_RE:
if (! preg_match($spec['pattern'], $val)) {
$fail[] = array('name' => $name,
'value' => $val,
'msg' => isset($spec['errmsg'])
? $spec['errmsg']
: 'Failed to match RE');
}
break;
case VRFY_FUNC:
if (isset($spec['args'])) {
$args = $spec['args']
} else {
$args = array();
}
array_unshift($args, $val);
if (! call_user_func_array($spec['func'], $args)) {
$fail[] = array('name' => $name, 'value' => $val,
'msg' => isset($spec['errmsg'])
? $spec['errmsg']
: "Failed to satisfy function '{$spec['func']}'.");
}
break;
...
default:
throw new InvalidArgumentException("{$spec['type']} is not a valid verification type (trying to verify input '$name').");
}
}
return $fail;
}
function validUSPhoneNum($candidate) {
$candidate = preg_replace('/\D+/', '', $candidate);
return preg_match('/(1\d{3})?\d{7}/', $candidate);
}
function validUKPhoneNum($candidate) {
$candidate = preg_replace('/\D+/g', '', $candidate);
return preg_match('/(\+44|0)([1-358-9]\d|60|7[05-9])\d{7,8}/', $candidate);
}
$specs = array(
'zip' => array('type' => VRFY_RE, 'pattern' => '/^\d{5}(?:-\d{4})?/'),
'phone' => array('type' => VRFY_FUNC, 'func' => 'validUSPhoneNum'),
...
);
try {
$verifyErrors = verify($specs);
} catch (InvalidArgumentException $iae) {
error_log($iae);
echo "An internal error occurred. Sorry about that; it's been logged, and we'll look into it.";
}