Created
October 2, 2021 20:52
-
-
Save AyresMonteiro/b008006781030063aa1cbc42519dac15 to your computer and use it in GitHub Desktop.
A PHP Function that validates Brazil's 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 | |
function validateCNPJ($cnpj) | |
{ | |
$parsedCNPJ = preg_replace("/[.\/-]/", "", $cnpj); | |
if (!preg_match("/^\d{14}$/", $parsedCNPJ)) { | |
return false; | |
} | |
$weights = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]; | |
$digits = [0, 0]; | |
for ($i = 12; $i < 14; $i++) { | |
if ($i === 13) { | |
$weights = [6, ...$weights]; | |
} | |
for ($j = 0; $j < $i; $j++) { | |
if ($j < 12) { | |
$digits[$i - 12] += intval($parsedCNPJ[$j]) * $weights[$j]; | |
} else { | |
$digits[1] += $digits[0] * $weights[$j]; | |
} | |
} | |
$digits[$i - 12] %= 11; | |
if ($digits[$i - 12] < 2) { | |
$digits[$i - 12] = 0; | |
} else { | |
$digits[$i - 12] = 11 - $digits[$i - 12]; | |
} | |
} | |
$firstDigitIsValid = $digits[0] === intval($parsedCNPJ[12]); | |
$secondDigitIsValid = $digits[1] === intval($parsedCNPJ[13]); | |
return $firstDigitIsValid && $secondDigitIsValid; | |
} | |
// Random CNPJ number generated at https://www.4devs.com.br/gerador_de_cnpj | |
$randomCorrectCNPJ = "37.741.477/0001-38"; | |
$randomBrokeCNPJ = "37.741.477/0001-37"; | |
// Will echo 1 | |
echo validateCNPJ($randomCorrectCNPJ); | |
// Will echo 0 | |
echo validateCNPJ($randomBrokeCNPJ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment