Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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'));
@reginaldojunior

This comment has been minimized.

Copy link

@reginaldojunior reginaldojunior commented Nov 28, 2015

👍

@thiagolcks

This comment has been minimized.

Copy link

@thiagolcks thiagolcks commented Dec 10, 2015

Obrigado!

@rhagni

This comment has been minimized.

Copy link

@rhagni rhagni commented May 30, 2016

Muitíssimo obrigado 👍

@lucas-marciano

This comment has been minimized.

Copy link

@lucas-marciano lucas-marciano commented Jul 13, 2016

Vlws cara, foi show!

@anapaulafrancisco

This comment has been minimized.

Copy link

@anapaulafrancisco anapaulafrancisco commented Aug 12, 2016

Obrigada

@marcosfreitas

This comment has been minimized.

Copy link

@marcosfreitas marcosfreitas commented Aug 15, 2016

me economizou um tempinho... thanks.

@jhonata-menezes-forseti

This comment has been minimized.

Copy link

@jhonata-menezes-forseti jhonata-menezes-forseti commented Oct 5, 2016

Obrigado, irei deixar a referencia.

@lira92

This comment has been minimized.

Copy link

@lira92 lira92 commented Nov 26, 2016

👍

@sandroneuhaus

This comment has been minimized.

Copy link

@sandroneuhaus sandroneuhaus commented Feb 4, 2017

👍👍 Muito Bom, já usava outros métodos que eventualmente davam erro na validação, este seu método vem funcionando perfeitamente. Parabéns!!!

@marceloolima

This comment has been minimized.

Copy link

@marceloolima marceloolima commented Mar 12, 2017

Obrigado

@marcosjrlopez

This comment has been minimized.

Copy link

@marcosjrlopez marcosjrlopez commented Mar 14, 2017

Obrigado, mano!

@juniormartinxo

This comment has been minimized.

Copy link

@juniormartinxo juniormartinxo commented Mar 19, 2017

Muito bom, só faltou invalidar as sequências:

// Lista de CNPJs inválidos
$invalidos = [
	'00000000000000',
	'11111111111111',
	'22222222222222',
	'33333333333333',
	'44444444444444',
	'55555555555555',
	'66666666666666',
	'77777777777777',
	'88888888888888',
	'99999999999999'
];

// Verifica se o CNPJ está na lista de inválidos
if (in_array($cnpj, $invalidos)) {	
	return false;
}
@junta1

This comment has been minimized.

Copy link

@junta1 junta1 commented Jul 12, 2017

Obrigado!

@ggwebdev

This comment has been minimized.

Copy link

@ggwebdev ggwebdev commented Aug 12, 2017

Grato man! Com o ajuste do @junioraluisio ficou 100%

@wesmes

This comment has been minimized.

Copy link

@wesmes wesmes commented Aug 18, 2017

Muito bom! Valeu, obrigado!

@ricardofadini

This comment has been minimized.

Copy link

@ricardofadini ricardofadini commented Nov 24, 2017

Nice!

@g1llz

This comment has been minimized.

Copy link

@g1llz g1llz commented Jan 24, 2018

Muito bom!

@ftbraian

This comment has been minimized.

Copy link

@ftbraian ftbraian commented Feb 23, 2018

VALEW!

@sJonatas

This comment has been minimized.

Copy link

@sJonatas sJonatas commented Mar 1, 2018

(y)

@apandrade

This comment has been minimized.

Copy link

@apandrade apandrade commented Jun 19, 2018

// Verifica se todos os digitos são iguais
if (preg_match('/(\d)\1{13}/', $cnpj))
    return false;
@rickslayer

This comment has been minimized.

Copy link

@rickslayer rickslayer commented Aug 25, 2018

tks

@smourao

This comment has been minimized.

Copy link

@smourao smourao commented Sep 7, 2018

Muito bom, tnks.

@rodrigoalmeidanet

This comment has been minimized.

Copy link

@rodrigoalmeidanet rodrigoalmeidanet commented Nov 2, 2018

Muito bom rapaz... funciona perfeito. Adiciona o complemento do @apandrade que fica perfeito!

@akamus

This comment has been minimized.

Copy link

@akamus akamus commented Nov 29, 2018

Valeu galera do bem!

@joaorolim

This comment has been minimized.

Copy link

@joaorolim joaorolim commented Dec 5, 2018

Top! Obrigado!

@rogerpitigliani

This comment has been minimized.

Copy link

@rogerpitigliani rogerpitigliani commented Dec 14, 2018

Valeu!

@rogerionunes

This comment has been minimized.

Copy link

@rogerionunes rogerionunes commented Aug 28, 2019

Show! Valeu!

@brcontainer

This comment has been minimized.

Copy link

@brcontainer brcontainer commented Dec 2, 2019

Muito bom, só faltou invalidar as sequências:

// Lista de CNPJs inválidos
$invalidos = [
	'00000000000000',
	'11111111111111',
	'22222222222222',
	'33333333333333',
	'44444444444444',
	'55555555555555',
	'66666666666666',
	'77777777777777',
	'88888888888888',
	'99999999999999'
];

// Verifica se o CNPJ está na lista de inválidos
if (in_array($cnpj, $invalidos)) {	
	return false;
}

Não precisa, o if (preg_match('/(\d)\1{13}/', $cnpj)) já resolve isto.

@mateusmrosa

This comment has been minimized.

Copy link

@mateusmrosa mateusmrosa commented Dec 16, 2019

funcionou valeu

@luizbills

This comment has been minimized.

Copy link

@luizbills luizbills commented Mar 3, 2020

👍

@joefreire

This comment has been minimized.

Copy link

@joefreire joefreire commented Mar 23, 2020

Não funciona no php 7.4
Array and string offset access syntax with curly braces is deprecated

@luizbills

This comment has been minimized.

Copy link

@luizbills luizbills commented Mar 23, 2020

Não funciona no php 7.4
Array and string offset access syntax with curly braces is deprecated

só trocar os curly braces por chaves nas linhas 18, 30 e 36

@Uriel-Alves

This comment has been minimized.

Copy link

@Uriel-Alves Uriel-Alves commented Jun 24, 2020

Resolvido para PHP 7.4. Testei e estou utilizando o código com a API pagarme. 100% aprovado.

        $cnpj = preg_replace( '/[^0-9]/is', '', $cnpj );
        // Valida primeiro dígito verificador
        for ($i = 0, $j = 5, $soma = 0; $i < 12; $i++)
        {
            $soma += (int)$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 += (int)$cnpj[$i] * $j;
            $j = ($j == 2) ? 9 : $j - 1;
        }

        $resto = $soma % 11;

        return $cnpj[13] == ($resto < 2 ? 0 : 11 - $resto);

@srRodolfo

This comment has been minimized.

Copy link

@srRodolfo srRodolfo commented Jul 6, 2020

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;
}
@pferreirafabricio

This comment has been minimized.

Copy link

@pferreirafabricio pferreirafabricio commented Mar 11, 2021

Muito obrigado!

@rodriguesrenato61

This comment has been minimized.

Copy link

@rodriguesrenato61 rodriguesrenato61 commented Mar 26, 2021

Obrigado me ajudou muito!

@gitjorginho

This comment has been minimized.

Copy link

@gitjorginho gitjorginho commented Apr 8, 2021

Muito obrigado, Ajudou demais !

@tiagofrancafernandes

This comment has been minimized.

Copy link

@tiagofrancafernandes tiagofrancafernandes commented Jun 9, 2021

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;
}

top tbm

@tiagofrancafernandes

This comment has been minimized.

Copy link

@tiagofrancafernandes tiagofrancafernandes commented Jun 9, 2021

Obrigado

@LucianoCarbonera

This comment has been minimized.

Copy link

@LucianoCarbonera LucianoCarbonera commented Aug 31, 2021

Ótimo, Obrigado !!

@douglasisraelbonfim

This comment has been minimized.

Copy link

@douglasisraelbonfim douglasisraelbonfim commented Nov 10, 2021

public static function verificaCnpj(string $cnpj)
{
$url = "https://www.receitaws.com.br/v1/cnpj/" . $cnpj;
$json = file_get_contents($url);
return json_decode($json);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment