Last active
November 1, 2020 22:40
-
-
Save thyagofranca/78c7dee0f38aa33fd552014ae7eb7b89 to your computer and use it in GitHub Desktop.
Validação de CPF com 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($num_cpf) { | |
// Verifica se está vazio, e se não é caracteres numéricos | |
if(empty($num_cpf) && !is_numeric($num_cpf)) { | |
return false; | |
} | |
// Retorna apenas números | |
$num_cpf = preg_replace("/[^0-9]/is", "", $num_cpf); | |
// Verifica se foi informado todos os digitos corretamente | |
if (strlen($num_cpf) !== 11) { | |
return false; | |
} | |
// Verifica se u user digitou uma sequência de digitos repetidos. Ex: 999.999.999-99 | |
if(preg_match('/([0-9])\1{10}/', $num_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 += $num_cpf[$c] * (($t + 1) - $c); | |
} | |
$d = ((10 * $d) % 11) % 10; | |
if ($num_cpf[$c] != $d) { | |
return false; | |
} | |
} | |
return true; | |
} | |
# Para chamar o script valida-cpf.php em sua aplicação. | |
require_once("valida-cpf.php"); | |
#Adicione o trecho abaixo no seu arquivo de cadastro para validar o CPF. | |
$cpf = filter_input(INPUT_POST, "cpf", FILTER_SANITIZE_STRING); | |
//verifica se o cpf é valido | |
if(validaCPF($cpf])) { | |
echo "CPF válido"; | |
}else { | |
header("Location: seuscript.php?erro_cpf=1"); | |
exit(); | |
} | |
############################################# | |
// Caso queiram o sistema completo usando essa função e mais validações no banco de dados veja o link abaixo, espero que ajude. | |
// https://github.com/ThyagoFranca/sistema-de-cadastro-php-pdo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment