Last active
April 3, 2024 13:24
-
-
Save guisehn/3276302 to your computer and use it in GitHub Desktop.
Validar CNPJ (PHP)
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 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')); |
public static function verificaCnpj(string $cnpj) { $url = "https://www.receitaws.com.br/v1/cnpj/" . $cnpj; $json = file_get_contents($url); return json_decode($json); }
Show
Contribuindo com a resposta do @douglasisraelbonfim
use Illuminate\Support\Facades\Http;
public static function verificaCnpj(string $cnpj): array
{
$result = Http::get("https://www.receitaws.com.br/v1/cnpj/" . $cnpj);
return $result->json();
}
Olá, tudo bom? Deixo aqui uma pequena contribuição como forma de agradecimento!
/** * Valida CPNJ * @param string $document * @return bool */ function is_cnpj(string $document): bool { // Extrai os números $cnpj = preg_replace('/[^0-9]/is', '', $document); // Valida tamanho if (strlen($cnpj) != 14) { return false; } // Verifica sequência de digitos repetidos. Ex: 11.111.111/111-11 if (preg_match('/(\d)\1{13}/', $cnpj)) { return false; } // Valida dígitos verificadores for ($t = 12; $t < 14; $t++) { for ($d = 0, $m = ($t - 7), $i = 0; $i < $t; $i++) { $d += $cnpj[$i] * $m; $m = ($m == 2 ? 9 : --$m); } $d = ((10 * $d) % 11) % 10; if ($cnpj[$i] != $d) { return false; } } return true; }
Sensacional, ficou simples, valeu! (gostei como vc resolveu as sequencias inválidas)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
public static function verificaCnpj(string $cnpj)
{
$url = "https://www.receitaws.com.br/v1/cnpj/" . $cnpj;
$json = file_get_contents($url);
return json_decode($json);
}