novidades, artigos e tudo mais!
php
Classe PHP para integridade de dados.
18/02/10
Esse código é meio temporário, em breve eu coloco ele numa classe e disponibilizo para vocês:
Vocês podem usar este código a vontade nos trabalhos de vocês.
Vejam abaixo:
<?php
//Troca aspas simples por entities
function _no_single_quotes($str) {
return str_replace("'","'",$str);
}
//Retira as barras inversas
function _no_slashes($str) {
return str_replace("\\","",$str);
}
//Deixa a string somente com números
function _just_numbers($str) {
return ereg_replace("[^0-9]","",$str);
}
//Retira: espaços no início e fim, barras inversas
//Troca por entities: ampersand (&), aspas dupla ("), aspas simples ('), menor que (<), maior que (>)
function fix_string($str) {
return trim(_no_slashes(htmlspecialchars($str,ENT_QUOTES)));
}
//Trata uma string para ser usada em URLs ou nomes de arquivos
function fix_to_url($str) {
$str_lower = strtolower(trim($str)); //remove espaços do início e fim e deixa tudo em minúsculo
$strtr = strtr($str_lower, 'ÀÁÃÂÉÊÍÓÕÔÚÜÇÑàáãâéêíóõôúüçñ ','aaaaeeiooouucnaaaaeeiooouucn-'); //traduz alguns caracteres
$str_replace = ereg_replace('[^0-9a-z-]','',$strtr); //deixa a string apenas com alfa numéricos e com os traçõs (-)
return ereg_replace('-{1,}', '-', $str_replace); //retorna a string formatada para uma URL (aplica um novo replace para tirar os traços que ficaram em sequência (---) )
}
//Inversão entre os formatos dd/mm/yyyy e yyyy-mm-dd
function fix_date($date) {
$x = split("[^0-9]",$date);
$sep = (strlen($x[0]) <= 2)?"-":"/";
return $x[2].$sep.$x[1].$sep.$x[0];
}
//Formata um datetime para o padrão português Brasil
function fix_datetime($datetime) {
$x = explode(" ",$datetime);
return fix_date($x[0])." ".$x[1];
}
//Formatar o número de telefone/fax
function fix_phone($number) {
$x = _just_numbers($number);
if (strlen($x) >= 10) {
$final = substr($x,-4);
$pre = substr($x,-8,4);
$ddd = substr($x,-10,2);
return "($ddd) $pre-$final";
} else {
return $number;
}
}
//Formata o número do CPF
function fix_cpf($cpf) {
$cpf = _just_numbers($cpf);
return substr($cpf,0,3).".".substr($cpf,3,3).".".substr($cpf,6,3)."-".substr($cpf,9,2);
}
//Formata o número do CNPJ
function fix_cnpj($cnpj) {
$cnpj = _just_numbers($cnpj);
return substr($cnpj,0,2).".".substr($cnpj,2,3).".".substr($cnpj,5,3)."/".substr($cnpj,8,4)."-".substr($cnpj,12,2);
}
//Formata o CEP
function fix_cep($cep) {
$cep = _just_numbers($cep);
return substr($cep,0,5)."-".substr($cep,5,3);
}
//Retira atributos e tags (Útil para limpar o conteúdo submetido através de um textarea com o editor TinyMce)
//Utilize o parâmetro $tags para informar quais tags são aceitas e o parâmetro $attributes para informar quais atributos *não* são aceitos
function fix_html_text($text, $tags = array("b","strong","i","em","strike","ul","ol","li","blockquote","q","cite","a","img","object","param","embed","sub","sup","table","th","tr","td","caption","h1","h2","h3","h4","h5","h6","p","pre","address","br","hr"), $attributes = array("style")) {
$text = stripslashes($text); //Remove aspas de addslashes (o valor sempre será recebido com aspas, em /config/globals_cfg.php todos os $_POST são configurados para receber addslashes)
//Atributos não permitidos
foreach ($attributes as $attribute) {
preg_match_all("|$attribute=\"(.*)\"|U",$text,$out_not_allowed, PREG_PATTERN_ORDER);
foreach ($out_not_allowed[0] as $attribute_not_allowed) {
$attributes_not_allowed[] = $attribute_not_allowed;
}
}
//Array com todas as tags permitidas
foreach ($tags as $tag) {
$allowed_tags[] = "<$tag>";
}
$replace = str_replace($attributes_not_allowed,null,$text); //substitui por null todos os atributos não desejados
$replace2 = eregi_replace(" {1,}>",">",$replace); //retira algumas sobras, ex. <strong > para <strong>
$replace3 = eregi_replace(" {1,}"," ",$replace2); //substitui sequências de espaços por um espaço, ex. <img src="foto.jpg" /> para <img src="foto.jpg" />
$replace4 = eregi_replace("<[A-Za-z]{1,}>( | )?</[A-Za-z]{1,}>","",$replace3); //exclui tags vazias, ex. <p></p>, <div> </div>
$fixhtml = $replace4;
if($encoding == 'iso-8859-1'){
return _no_single_quotes(html_entity_decode(strip_tags($fixhtml,implode($allowed_tags))));
} else {
return _no_single_quotes(strip_tags($fixhtml,implode($allowed_tags)));
}
}
//Limita a quantidade de palavras de uma string
function word_limit($str, $limit = 100) {
$words = explode(" ",$str);
if (count($words) > $limit) {
for ($i = 0; $i <= $limit-1; $i++) {
$w[] = $words[$i];
}
return implode(" ",$w)."...";
} else {
return $str;
}
}
//Quebra uma string em linhas usando um caracter de quebra de linha
function word_wrap($str, $width = 75, $break = "<br />") {
return wordwrap($str,$width,$break,1);
}
//Checa se é um email válido
function is_email($email) {
return (preg_match("/^([a-zA-Z0-9._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/",$email))?true:false;
}
//Checa se é uma data válida
//Utilize o parâmetro $format para informar o formato da data a ser validada
function is_date($date, $format = "dd/mm/yyyy") {
$w = split("[^a-zA-Z0-9]",$format);
$x = split("[^0-9]",$date);
$z = (count($w) === count($x))?array_combine($w, $x):false;
return ($z and checkdate($z['mm'],$z['dd'],$z['yyyy']))?true:false;
}
//Checa se pode ser um telefone
function is_phone($number) {
return (strlen(_just_numbers($number)) >= 10)?true:false;
}
function is_cpf($cpf) {
/**
* Função para validar CPF (Cadastro de Pessoas Físicas)
*
* @author Paulo Ricardo F. Santos <v1d4l0k4.at.gmail.dot.com>
* @copyright Copyright © 2006, Paulo Ricardo F. Santos
* @license http://creativecommons.org/licenses/by-nc-sa/2.0/br Commons Creative
* @version 20070316
* @param string $cpf CPF que deseja validar
* @return bool true caso seje válido, false caso não seje válido
*/
$cpf = str_pad(ereg_replace('[^0-9]', '', $cpf), 11, '0', STR_PAD_LEFT);
if (strlen($cpf) != 11 || $cpf == '00000000000' || $cpf == '99999999999') {
return false;
} else {
for ($t = 9; $t < 11; $t++) {
for ($d = 0, $c = 0; $c < $t; $c++) {
$d += $cpf{$c} * (($t + 1) - $c);
}
$d = ((10 * $d) % 11) % 10;
if ($cpf{$c} != $d) {
return false;
}
}
return true;
}
}
function is_cnpj($cnpj) {
/**
* Função para validar CNPJ (Cadastro Nacional da Pessoa Jurídica)
*
* @author Paulo Ricardo F. Santos <v1d4l0k4.at.gmail.dot.com>
* @copyright Copyright © 2006, Paulo Ricardo F. Santos
* @license http://creativecommons.org/licenses/by-nc-sa/2.0/br Commons Creative
* @version 20070316
* @param string $cnpj CNPJ que deseja validar
* @return bool true caso seje válido, false caso não seje válido
*/
$cnpj = str_pad(ereg_replace('[^0-9]', '', $cnpj), 14, '0', STR_PAD_LEFT);
if (strlen($cnpj) != 14) {
return false;
} else {
for ($t = 12; $t < 14; $t++) {
for ($d = 0, $p = $t - 7, $c = 0; $c < $t; $c++) {
$d += $cnpj{$c} * $p;
$p = ($p < 3) ? 9 : --$p;
}
$d = ((10 * $d) % 11) % 10;
if ($cnpj{$c} != $d) {
return false;
}
}
return true;
}
}
//Verfica se a string pode ser um CEP (número com 8 dígitos)
function is_cep($cep) {
return (strlen(_just_numbers($cep)) == 8)?true:false;
}
//Verifica se a string pode ser uma imagem (baseado na extensão), não é verificado se o arquivo é realmente uma imagem
function is_img($str, $img_exts = array("JPG","JPEG","jpg","jpeg","GIF","gif","PNG","png")) {
$ext = _extension($str);
return (in_array($ext,$img_exts))?true:false;
}
?>