Skip to content

Instantly share code, notes, and snippets.

@elyezer
Created August 23, 2013 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elyezer/6319557 to your computer and use it in GitHub Desktop.
Save elyezer/6319557 to your computer and use it in GitHub Desktop.
Function that validates Brazilian CNPJ in PHP
<?
//------------------------------------------------------------------------------
// Description: Function that validates Brazilian CNPJ
// Author: Elyézer Mendes Rezende
// Inspired by:
// http://codigofonte.uol.com.br/codigos/validar-numero-do-cnpj
// https://github.com/django/django-localflavor/blob/master/localflavor/br/forms.py
//------------------------------------------------------------------------------
function validate_cnpj($cnpj) {
if (!is_numeric($cnpj)) {
$cnpj = preg_replace("/[-\/\.]/", "", $cnpj);
}
if (!intval($cnpj)) {
return false;
}
if (strlen($cnpj) <> 14) {
return false;
}
$soma1 = ($cnpj[0] * 5) +
($cnpj[1] * 4) +
($cnpj[2] * 3) +
($cnpj[3] * 2) +
($cnpj[4] * 9) +
($cnpj[5] * 8) +
($cnpj[6] * 7) +
($cnpj[7] * 6) +
($cnpj[8] * 5) +
($cnpj[9] * 4) +
($cnpj[10] * 3) +
($cnpj[11] * 2);
$resto = $soma1 % 11;
$digito1 = $resto < 2 ? 0 : 11 - $resto;
$soma2 = ($cnpj[0] * 6) +
($cnpj[1] * 5) +
($cnpj[2] * 4) +
($cnpj[3] * 3) +
($cnpj[4] * 2) +
($cnpj[5] * 9) +
($cnpj[6] * 8) +
($cnpj[7] * 7) +
($cnpj[8] * 6) +
($cnpj[9] * 5) +
($cnpj[10] * 4) +
($cnpj[11] * 3) +
($cnpj[12] * 2);
$resto = $soma2 % 11;
$digito2 = $resto < 2 ? 0 : 11 - $resto;
return (($cnpj[12] == $digito1) && ($cnpj[13] == $digito2));
}
// Testing
$data = array(
"64.132.916/0001-88" => true,
"64-132-916/0001-88" => true,
"64132916/0001-88" => true,
"12-345-678/9012-10" => false,
"12.345.678/9012-10" => false,
"12345678/9012-10" => false,
"64.132.916/0001-XX" => false,
);
foreach ($data as $cnpj => $valid) {
print("Validating $cnpj... ");
if (validate_cnpj($cnpj) === $valid) {
print("OK\n");
} else {
print("FAIL\n");
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment