Skip to content

Instantly share code, notes, and snippets.

@lenivene
Created March 26, 2019 16:11
Show Gist options
  • Save lenivene/519ba7068940044dbb95cd1ff6bd071f to your computer and use it in GitHub Desktop.
Save lenivene/519ba7068940044dbb95cd1ff6bd071f to your computer and use it in GitHub Desktop.
Verificar se o CNPJ ( Cadastro nacional de pessoas Jurídicas ) é um número valido.
<?php
/**
* Verificar se o CNPJ ( Cadastro nacional de pessoas Jurídicas ) é um número valido.
*
* @author Lenvene Bezerra
* @return true | false
*/
function is_cnpj( $cnpj ){
if( ! isset( $cnpj ) || isset( $cnpj ) && empty( $cnpj ) )
return false;
// Retorna só os números
$cnpj = preg_replace( '/[^0-9]/', '', $cnpj );
/**
* CNPJ tem 14 digitos, verifica se não é 14.
* Verifica se foi informada uma sequência de digitos repetidos.
*/
if( mb_strlen( $cnpj ) != 14 || preg_match( '/(\d)\1{13}/', $cnpj ) )
return false;
/**
* Calculo para validar o CNPJ
*/
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 (bool) ( $cnpj{13} == ( $resto < 2 ? 0 : 11 - $resto ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment