Last active
May 17, 2016 17:19
-
-
Save mariovalney/f96e514cbe678be9dcf0a3be7857f364 to your computer and use it in GitHub Desktop.
CPF and CNPJ validation (back-end)
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 | |
/** | |
* Função que checa se um CPF é válido | |
* Criado em fevereiro/2016 | |
*/ | |
function check_cpf_is_valid( $string ) { | |
$cpf = pm_sanitize_number($string); | |
if (strlen($cpf) != 11) { | |
return false; | |
} | |
$digitoTestado = substr($cpf, 9, 2); | |
$digitoValidado = ''; | |
$sum1 = $sum2 = $dig1 = $dig2 = 0; | |
for ($i = 0; $i < 10; $i++) { | |
if ($i < 9) { | |
$sum1 += substr($cpf, $i, 1) * (10 - $i); | |
} | |
$sum2 += substr($cpf, $i, 1) * (11 - $i); | |
}; | |
if ( ($sum1 % 11) >= 2 ) { | |
$dig1 = 11 - ($sum1 % 11); | |
} | |
if ( ($sum2 % 11) >= 2 ) { | |
$dig2 = 11 - ($sum2 % 11); | |
} | |
$digitoValidado = $dig1 . $dig2; | |
if ( $digitoTestado === $digitoValidado ) { | |
return true; | |
} | |
return false; | |
} | |
/** | |
* Função que checa se um CNPJ é válido | |
* Criado em fevereiro/2016 | |
*/ | |
function check_cnpj_is_valid( $string ) { | |
$cnpj = pm_sanitize_number($string); | |
if (strlen($cnpj) != 14) { | |
return false; | |
} | |
$digitoTestado = substr($cnpj, 12, 2); | |
$digitoValidado = ''; | |
$sum1 = $sum2 = $dig1 = $dig2 = 0; | |
$second_row = array(6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2); | |
for ($i = 0; $i < 13; $i++) { | |
if ($i < 12) { | |
$sum1 += substr($cnpj, $i, 1) * $second_row[($i + 1)]; | |
} | |
$sum2 += substr($cnpj, $i, 1) * $second_row[$i]; | |
}; | |
if ( ($sum1 % 11) >= 2 ) { | |
$dig1 = 11 - ($sum1 % 11); | |
} | |
if ( ($sum2 % 11) >= 2 ) { | |
$dig2 = 11 - ($sum2 % 11); | |
} | |
$digitoValidado = $dig1 . $dig2; | |
if ( $digitoTestado === $digitoValidado ) { | |
return true; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment