Created
May 23, 2012 22:30
-
-
Save pedroelsner/2778237 to your computer and use it in GitHub Desktop.
Sanitize for PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Classe que contem os métodos que iram | |
* filtrar as entradas enviadas via GET e POST | |
* | |
* @filesource | |
* @author Pedro Elsner <[email protected]> | |
* @license http://creativecommons.org/licenses/by/3.0/br/ Creative Commons 3.0 | |
* @abstract | |
* @version 1.0 | |
*/ | |
abstract class Sanitize { | |
/** | |
* Filter | |
* | |
* @param mixed $value | |
* @param array $modes | |
* @return mixed | |
* @static | |
* @since 1.0 | |
*/ | |
static public function filter($value, $modes = array('sql', 'html')) { | |
if (!is_array($modes)) { | |
$modes = array($modes); | |
} | |
if (is_string($value)) { | |
foreach ($modes as $type) { | |
$value = self::_doFilter($value, $type); | |
} | |
return $value; | |
} | |
foreach ($value as $key => $toSanatize) { | |
if (is_array($toSanatize)) { | |
$value[$key]= self::filter($toSanatize, $modes); | |
} else { | |
foreach ($modes as $type) { | |
$value[$key] = self::_doFilter($toSanatize, $type); | |
} | |
} | |
} | |
return $value; | |
} | |
/** | |
* DoFilter | |
* | |
* @param mixed $value | |
* @param array $modes | |
* @return mixed | |
* @static | |
* @since 1.0 | |
*/ | |
static protected function _doFilter($value, $mode) { | |
switch ($mode) { | |
case 'html': | |
$value = strip_tags($value); | |
$value = addslashes($value); | |
$value = htmlspecialchars($value); | |
break; | |
case 'sql': | |
$value = preg_replace(sql_regcase('/(from|select|insert|delete|where|drop table|show tables|#|\*| |\\\\)/'),'',$value); | |
$value = trim($value); | |
break; | |
} | |
return $value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Antes de mais nada, venho agradecer pelo gist. Me ajudou muito.
Só encontrei um pequeno problema que ocorre ao filtrar uma variável do tipo array (como os $_GET e $_POST):
Entre as linhas 40 e 42, cada vez que o foreach itera, um novo $type é passado ignorando o conteúdo posterior da variável $value[$key] que havia sido filtrada.
Usei uma variável para armazenar o resultado previamente filtrado