Skip to content

Instantly share code, notes, and snippets.

@hussani
Created June 10, 2015 18:53
Show Gist options
  • Save hussani/792251cfb199cf278281 to your computer and use it in GitHub Desktop.
Save hussani/792251cfb199cf278281 to your computer and use it in GitHub Desktop.
PHP function to validade a CNPJ
<?php
function validateCnpj($cnpj)
{
$cnpj = preg_replace('/[^0-9]/', '', (string) $cnpj);
if (strlen($cnpj) != 14) {
return false;
}
for ($i = 0, $j = 5, $sum = 0; $i < 12; $i++) {
$sum += $cnpj[$i] * $j;
$j = ($j == 2) ? 9 : $j - 1;
}
$rest = $sum % 11;
if ($cnpj[12] != ($rest < 2 ? 0 : 11 - $rest)) {
return false;
}
for ($i = 0, $j = 6, $sum = 0; $i < 13; $i++) {
$sum += $cnpj[$i]
* $j;
$j = ($j == 2) ? 9 : $j - 1;
}
$rest = $sum % 11;
return $cnpj[13] == ($rest < 2 ? 0 : 11 - $rest);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment