Skip to content

Instantly share code, notes, and snippets.

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 RodrigoPauletti/8dbd143179d4d2baa95475e677a814ab to your computer and use it in GitHub Desktop.
Save RodrigoPauletti/8dbd143179d4d2baa95475e677a814ab to your computer and use it in GitHub Desktop.
Validar CNPJ (PHP)
<?php
function validar_cnpj($cnpj)
{
$cnpj = preg_replace('/[^0-9]/', '', (string) $cnpj);
// Valida tamanho
if (strlen($cnpj) != 14)
return false;
// Verifica se todos os digitos são iguais
if (preg_match('/(\d)\1{13}/', $cnpj))
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);
}
var_dump(validar_cnpj('11.444.777/0001-61'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment