Created
March 26, 2019 16:11
-
-
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.
This file contains hidden or 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 | |
/** | |
* 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