我有一个简单的清理函数,它在一个foreach语句中嵌入一个switch语句,我在某处读到这是一个不好的做法,但是我还没有能够提出更好的解决方案,我的代码如下,任何帮助将不胜感激...
public static function DB_Sanitize($input, $santype = 'SQL', $cleanKeys = FALSE) {
$type = strtoupper($santype);
if (!is_array($input)) {
$input = array($input);
}
foreach ($input as $key => $value) {
switch ($type) {
case 'SQL':
if ($cleanKeys) {
$key = $this->_mysqli->escape_string($key);
}
$value = $this->_mysqli->escape_string($value);
$clean[$key] = $value;
break;
case 'HTML':
if ($cleanKeys) {
$key = htmlentities($key);
}
$value = htmlentities($value);
$clean[$key] = $value;
break;
default:
if ($cleanKeys) {
$key = $this->_mysqli->escape_string($key);
}
$value = $this->_mysqli->escape_string($value);
$clean[$key] = $value;
break;
}
return $clean;
}
答案 0 :(得分:0)
public function DB_Sanitize($input, $context = 'SQL', $cleanKeys = FALSE) {
$type = gettype($input);
$context = strtoupper($context);
if (!is_array($input)) {
$input = array($input);
}
switch($context) {
case 'SQL':
$filter = array('options' => array($this->_mysqli, 'escape_string'));
break;
case 'HTML':
$filter = 'html_entities';
break;
default:
$filter = array('options' => array($this->_mysqli, 'escape_string'));
break;
}
foreach ($input as $key => $value) {
if ($type == 'string') $strkey = $key;
if ($cleanKeys && is_string($key)) {
$key = filter_var($key, FILTER_CALLBACK, $filter);
}
$value = filter_var($value, FILTER_CALLBACK, $filter);
$clean[$key] = $value;
}
if (isset($strkey)) return $clean[$strkey];
return $clean;
}