-
-
Save brunoleles/e15c2922b5d9de12fcdd to your computer and use it in GitHub Desktop.
Validar CPF (PHP)
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 | |
function validate_cpf($cpf) { | |
$cpf = preg_replace('/[^0-9]/', '', (string) $cpf); | |
$cpf = str_pad($cpf, 11, '0', STR_PAD_LEFT); | |
// CPF Invalido | |
if ($cpf === '00000000000') { | |
return false; | |
} | |
// Valida tamanho | |
if (strlen($cpf) != 11) { | |
return false; | |
} | |
// Calcula e confere primeiro dígito verificador | |
for ($i = 0, $j = 10, $soma = 0; $i < 9; $i++, $j--) { | |
$soma += $cpf{$i} * $j; | |
} | |
$resto = $soma % 11; | |
if ($cpf{9} != ($resto < 2 ? 0 : 11 - $resto)) { | |
return false; | |
} | |
// Calcula e confere segundo dígito verificador | |
for ($i = 0, $j = 11, $soma = 0; $i < 10; $i++, $j--) { | |
$soma += $cpf{$i} * $j; | |
} | |
$resto = $soma % 11; | |
if ($cpf{10} == ($resto < 2 ? 0 : 11 - $resto)) { | |
return $cpf; | |
} | |
return false; | |
} | |
var_dump(validate_cpf('111.444.777-35')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment