Created
January 23, 2020 13:29
-
-
Save franciscopessoa/514250f04d84c36b2cefef56ea7865f8 to your computer and use it in GitHub Desktop.
Validador CPF e 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 __validaCPF($cpf) | |
{ | |
# Retira da string tudo que não estiver entre 0 e 9 | |
$cpf = preg_replace('/[^0-9]/', '', (string) $cpf); | |
# Verifica tamano da string e se todos os digitos são iguais | |
if (strlen($cpf) !== 11 or preg_match('/(\d)\1{10}/', $cpf)) { | |
return false; | |
} | |
# Calculo para validar CPF | |
for ($t = 9; $t < 11; $t++) { | |
for ($d = 0, $c = 0; $c < $t; $c++) { | |
$d += $cpf[$c] * (($t + 1) - $c); | |
} | |
$d = ((10 * $d) % 11) % 10; | |
if ($cpf[$c] != $d) { | |
return false; | |
} | |
} | |
return true; | |
} | |
function __validaCNPJ($cnpj) | |
{ | |
# Retira da string tudo que não estiver entre 0 e 9 | |
$cnpj = preg_replace('/[^0-9]/', '', (string) $cnpj); | |
# Verifica tamano da string e se todos os digitos são iguais | |
if (strlen($cnpj) != 14 or 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment