-
-
Save fellypsantos/4df48645265e25647ec9371e9909e75f to your computer and use it in GitHub Desktop.
Validar CPF em PHP (Completo)
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) { | |
// Extrai somente os números | |
$cpf = preg_replace( '/[^0-9]/is', '', $cpf ); | |
// Verifica se foi informado todos os digitos corretamente | |
if (strlen($cpf) != 11) { | |
return false; | |
} | |
// Verifica se foi informada uma sequência de digitos repetidos. Ex: 111.111.111-11 | |
if (preg_match('/(\d)\1{10}/', $cpf)) { | |
return false; | |
} | |
// Faz o calculo para validar o 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment