I've created a class that's used for cleaning variables for use. You set a name, value and options and it will set the value if it matches the criteria/options.
It is used like this:
$var = new Variable();
$var->clean('username', $_POST['username'], '3,13,alphanumeric,True');
echo 'Username', $var->clean("username");
echo 'Username', $var->html("username");
It seems very messy and as though it could be done in a better way.
<?php
include_once __DIR__ . '/header.php';
class Variable
{
var $clean = array(); // Filtered data
var $html = array(); // Escaped htmlentities() data
/**
* variable->addClean()
*
* @param mixed $name - Name of clean value
* @param mixed $value - Value to clean
* @param string $options - Options in the format specified
* @return mixed - Clean value.
*
* Options format:
* {min length} - set to -1 to ignore.
* {max length} - set to -1 to ignore.
* {type} - set to null to ignore. Types:
* - Numeric.
* - AlphaNumeric.
* - Alpha.
* {trim} - default is true.
*
* eg.
* $var = new Variable();
* $var->clean('username', $_POST['username'], '3,13,alphanumeric,True');
* echo 'Username', $var->clean("username");
*
*/
public function clean($name, $value = null, $options = '')
{
if ($value === null && $name !== null)
return isset($this->clean[$name]) ? $this->clean[$name] : null;
else if ($value !== null && $name !== null) {
if (!empty($options)) {
list($minlen, $maxlen, $type, $trim) = array_pad(explode(',', (string)$options), 4, '');
if (strtolower($trim) !== 'false')
$value = trim($value);
if ($minlen !== '-1')
if (!(strlen($value) > $minlen))
return false;
if ($maxlen !== '-1')
if (!(strlen($value) < $maxlen))
return false;
switch (strtolower($type)) {
case 'numeric':
if (is_numeric($value))
$this->clean[$name] = intval($value);
break;
case 'alphanumeric':
if (ctype_alnum($value))
$this->clean[$name] = $value;
break;
case 'alpha':
if (ctype_alpha($value))
$this->clean[$name] = $value;
break;
default:
$this->clean[$name] = $value;
break;
}
} else
$this->clean[$name] = $value;
}
return isset($this->clean[$name]);
}
public function isClean($name)
{
return isset($this->clean[$name]);
}
public function html($name)
{
if (!isset($this->html[$name]) && isset($this->clean[$name]))
$this->html[$name] = htmlentities($this->clean[$name], ENT_QUOTES, 'UTF-8');
return (isset($this->html[$name]) ? $this->html[$name] : null);
}
}