Skip to content

Instantly share code, notes, and snippets.

@scardine
Last active October 6, 2015 14:38
Show Gist options
  • Save scardine/3008329 to your computer and use it in GitHub Desktop.
Save scardine/3008329 to your computer and use it in GitHub Desktop.
CPF/CNPJ Validation
/*
O algoritmo para validação do CPF e CNPJ é
bem conhecido, portanto a preocupação de tornar
o código legível foi sacrificada em prol de tornar
o código compacto.
Ambas as funções recebem uma string e retornam
TRUE ou FALSE dependendo do dígito de verificação
bater ou não.
*/
function xtend_valida_cpf($cpf) {
$cpf = str_pad(preg_replace('/\D/', '', $cpf), 11, '0', STR_PAD_LEFT);
if(strlen($cpf) != 11 || $cpf == str_repeat($cpf[0], 11)) return FALSE;
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[$t] != $d) return FALSE;
}
return TRUE;
}
function xtend_valida_cnpj($cnpj) {
$cnpj = str_pad(preg_replace('/\D/', '', $cnpj), 15, '0', STR_PAD_LEFT);
if(strlen($cnpj) != 15 || $cnpj == str_repeat($cnpj[0], 15)) return FALSE;
for($s1=0, $i=12, $j=2; $i>0; $i--) {
$s1 += $cnpj[$i] * $j; $j++;
if($j > 9) $j = 2;
}
$r = $s1 % 11;
if($cnpj[13] != ($r < 2 ? 0 : 11 - $r)) return FALSE;
for($s2=0, $i=13, $j=2; $i>0; $i--) {
$s2 += $cnpj[$i] * $j; $j++;
if($j > 9) $j = 2;
}
$r = $s2 % 11;
return $cnpj[14] == ($r < 2 ? 0 : 11 - $r);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment