-
-
Save guisehn/3276015 to your computer and use it in GitHub Desktop.
<?php | |
function validar_cpf($cpf) | |
{ | |
$cpf = preg_replace('/[^0-9]/', '', (string) $cpf); | |
// 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; | |
return $cpf{10} == ($resto < 2 ? 0 : 11 - $resto); | |
} | |
var_dump(validar_cpf('111.444.777-35')); |
Cheguei a este gist enquanto buscava sobre o assunto, mas achei interessante considerar o uso dessa biblioteca: https://github.com/Respect/Validation/blob/master/library/Respect/Validation/Rules/Cpf.php
Estou iniciando em php, alguem poderia postar um exemplo de uso?
Meu velho faz uma melhora básica no seu código com o seguinte:
$invalidos = array('00000000000',
'11111111111',
'22222222222',
'33333333333',
'44444444444',
'55555555555',
'66666666666',
'77777777777',
'88888888888',
'99999999999');
if (in_array($cpf, $invalidos))
return false;
Chegando a esse Gist vi que não era completo então criei outra versão.
https://gist.github.com/rafael-neri/ab3e58803a08cb4def059fce4e3c0e40
Meu velho faz uma melhora básica no seu código com o seguinte:
$invalidos = array('00000000000',
'11111111111',
'22222222222',
'33333333333',
'44444444444',
'55555555555',
'66666666666',
'77777777777',
'88888888888',
'99999999999');
if (in_array($cpf, $invalidos))
return false;
Mais simples fazer assim:
if ( preg_match ( '/(\d)\1{10}/', $cpf ) ) return false;
Tem algumas brechas como CNPJ 00000000000 (ou 99999999999999, 33333333, etc)