Hi,
Just one little class I made to control user's submitted datas, I thought it could help some people with security.
And if anyone wants to improve it, I'd be glad you do so.
<?php
define('REG_DATE' , '([[:digit:]]{4})-([[:digit:]]{2})-([[:digit:]]{2})');
define('REG_DIGIT_SIGNED' , '^[-[:digit:]]+$');
define('REG_DIGIT_UNSIGNED', '^[[:digit:]]+$');
define('REG_PASSWORD' , '^[[:alnum:]]+$');
define('REG_TEXT' , '[[:graph:][:blank:]]+');
define('REG_WORD' , '^[[:alpha:]]+$');
final class checkVar{
private $tmp; private function isSet(&$field){
if(!isset($_REQUEST[$field]))
throw new Exception("You forgot to fill the $field field.");
else
return true;
}
private function removeCharsThreats(&$field){
$this->tmp = trim($_REQUEST[$field]);
$this->tmp = htmlspecialchars($_REQUEST[$field], ENT_QUOTES, 'UTF-8', false);
}
public function securityBool($field){
if($this->isSet($field) && $_REQUEST[$field] != 1)
throw new Exception("Unallowed value in $field field.");
else
return true;
}
public function securityEnum($field, $enum){
if($this->isSet($field)){
$this->removeCharsThreats($field);
$tab = explode(',', $enum);
if(!in_array($this->tmp, $tab))
throw new Exception("Unallowed value in $field field.");
else
return (string) $this->tmp;
}
}
public function securityRange($field, $range){
if($this->isSet($field)){
$this->removeCharsThreats($field);
$tab = explode('/', $range);
if(!is_numeric($this->tmp))
throw new Exception("Unallowed characters in $field field.");
elseif($this->tmp < $tab[0] || $this->tmp > $tab[1])
throw new Exception('Value must be in range '.$tab[0].'/'.$tab[1]." in $field field.");
else
return (int) $this->tmp;
}
}
public function securityText($field, $maxlength, $regexp){
if($this->isSet($field)){
$this->removeCharsThreats($field);
if(!mb_ereg($regexp, $this->tmp))
throw new Exception("Unallowed characters in $field field.");
elseif(mb_strlen($this->tmp, ENCODING) > $maxlength)
throw new Exception("Too long string length for $field field.");
else
return $this->tmp;
}
}
}
?>
Here are some examples of how to use the public methods.
<?php
$checkVar = new checkVar();
$args = array();
$args['bbexport'] = $checkVar->securityBool('bbexport');
$args['id'] = (int) $checkVar->securityText('id', 4, REG_DIGIT_UNSIGNED);
$args['orderBy'] = $checkVar->securityEnum('orderBy', 'date,id,name');
$args['ratio'] = $checkVar->securityRange('ratio', '0/10');
?>