Skip to content

Instantly share code, notes, and snippets.

@robertopc
Forked from guisehn/gist:3276015
Last active August 9, 2018 01:28
Show Gist options
  • Save robertopc/e231866361fae2148934 to your computer and use it in GitHub Desktop.
Save robertopc/e231866361fae2148934 to your computer and use it in GitHub Desktop.
Validar CPF (PHP)
<?php
function validar_cpf($cpf)
{
$cpf = preg_replace('/\D/', '', (string) $cpf);
// Valida tamanho
if (strlen($cpf) != 11)
return false;
// se total de números
for($n=0;$n<10;$n++)
if( $cpf == str_repeat($n,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'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment