0

我有一个简单的清理函数,它在我在某处读到的 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;
}
4

1 回答 1

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;

}
于 2013-08-28T18:23:40.910 回答