Created
November 8, 2018 11:55
-
-
Save helderferrari2/c7eeda1512f2ab7d48f23eb2b34e6377 to your computer and use it in GitHub Desktop.
This file contains 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
public function validarCnpj($cnpj) | |
{ | |
$cnpj = preg_replace('/[^0-9]/', '', (string) $cnpj); | |
// Valida tamanho | |
if (strlen($cnpj) != 14) { | |
return false; | |
} | |
// Lista de CNPJs inválidos | |
$invalidos = [ | |
'00000000000000', | |
'11111111111111', | |
'22222222222222', | |
'33333333333333', | |
'44444444444444', | |
'55555555555555', | |
'66666666666666', | |
'77777777777777', | |
'88888888888888', | |
'99999999999999', | |
]; | |
// Verifica se o CNPJ está na lista de inválidos | |
if (in_array($cnpj, $invalidos)) { | |
return false; | |
} | |
// Valida primeiro dígito verificador | |
for ($i = 0, $j = 5, $soma = 0; $i < 12; $i++) { | |
$soma += $cnpj{$i} * $j; | |
$j = ($j == 2) ? 9 : $j - 1; | |
} | |
$resto = $soma % 11; | |
if ($cnpj{12} != ($resto < 2 ? 0 : 11 - $resto)) { | |
return false; | |
} | |
// Valida segundo dígito verificador | |
for ($i = 0, $j = 6, $soma = 0; $i < 13; $i++) { | |
$soma += $cnpj{$i} * $j; | |
$j = ($j == 2) ? 9 : $j - 1; | |
} | |
$resto = $soma % 11; | |
return $cnpj{13} == ($resto < 2 ? 0 : 11 - $resto); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment