Skip to content

Instantly share code, notes, and snippets.

@guisehn
Created August 6, 2012 16:13
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save guisehn/3276015 to your computer and use it in GitHub Desktop.
Save guisehn/3276015 to your computer and use it in GitHub Desktop.
Validar CPF (PHP)
<?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'));
@enapupe
Copy link

enapupe commented Apr 30, 2014

Tem algumas brechas como CNPJ 00000000000 (ou 99999999999999, 33333333, etc)

@giovannipds
Copy link

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

@aliceandrade
Copy link

Estou iniciando em php, alguem poderia postar um exemplo de uso?

@rosivaldo
Copy link

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;

@rafael-neri
Copy link

Chegando a esse Gist vi que não era completo então criei outra versão.
https://gist.github.com/rafael-neri/ab3e58803a08cb4def059fce4e3c0e40

@eduardokraus
Copy link

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;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment