php sanitize an array with a given function -
i have simple sanitize function nests switch statement inside of foreach statement read somewhere bad practice, haven't been able come better solution, code follows, appreciated...
public static function db_sanitize($input, $santype = 'sql', $cleankeys = false) { $type = strtoupper($santype); if (!is_array($input)) { $input = array($input); } foreach ($input $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; }
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 $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; }
Comments
Post a Comment