Created
June 30, 2012 14:15
-
-
Save jcemer/3023900 to your computer and use it in GitHub Desktop.
Receita Federal - CPF e CNPJ
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
<?php | |
/* | |
Cadastros da Receita Federal do Brasil | |
* Cadastro de Pessoas Físicas - CPF | |
* Cadastro Nacional Pessoa Jurídica - CNPJ | |
Por Jean Carlo Emer | |
*/ | |
class receitaFederal { | |
public static function isCPF($num) { | |
$num = preg_replace('/[^0-9]/', '', $num); | |
if (preg_match('/(\d)\\1{10}/', $num) || '12345678909' == $num) { | |
return false; | |
} | |
return strlen($num) == 11 | |
&& receitaFederal::_($num, 9) | |
&& receitaFederal::_($num, 10); | |
} | |
public static function isCNPJ($num) { | |
$num = preg_replace('/[^0-9]/', '', $num); | |
$num = preg_replace('/^\d?(\d{14})$/', '\\1', $num); | |
return strlen($num) == 14 | |
&& receitaFederal::_($num, 12, true) | |
&& receitaFederal::_($num, 13, true); | |
} | |
private static function _($num, $dig, $isCnpj = false) { | |
$sum = 0; | |
for ($i = 0; $i < $dig; $i++) { | |
$vl = $dig + 1 - $i; | |
if ($isCnpj && $vl > 9) { | |
$vl %= 8; | |
} | |
$sum += intval($num[$i]) * $vl; | |
} | |
$res = 11 - ($sum % 11); | |
return ($res > 9 ? 0 : $res) == intval($num[$dig]); | |
} | |
} | |
/* | |
All numbers were caught in google | |
*/ | |
echo '<h1>CPF</h1>'; | |
$cpf = array('11111111111', '12345678909', '117.471.451-49', '219.333.321-15', '142.821.510-72', '331.462.761-00'); | |
foreach ($cpf as $num) { | |
echo receitaFederal::isCPF($num) ? 'true' : 'false'; | |
echo '<br>'; | |
} | |
echo '<h1>CNPJ</h1>'; | |
$cnpj = array('038.896.711/0001-69', '002.356.143/0001-66', '01.652.197/0001-06', '76.068.055/0013-39', '10.426.518/0001-45', '04.116.056/0001-67'); | |
foreach ($cnpj as $num) { | |
echo receitaFederal::isCNPJ($num) ? 'true' : 'false'; | |
echo '<br>'; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Função compacta e funcional.