Skip to content

Instantly share code, notes, and snippets.

@fabiomontefuscolo
Created July 20, 2011 18:36
Show Gist options
  • Save fabiomontefuscolo/1095584 to your computer and use it in GitHub Desktop.
Save fabiomontefuscolo/1095584 to your computer and use it in GitHub Desktop.
verifica se cpf é válido
<?php
/** Return true if supplied cpf is valid or give an error message otherwise */
function is_a_valid_cpf($cpf) {
$error = __("O CPF fornecido é inválido.");
$cpf = preg_replace('/[^0-9]/','',$cpf);
if(strlen($cpf) != 11 || preg_match('/^([0-9])\1+$/', $cpf)) {
return $error;
}
// 9 primeiros digitos do cpf
$digit = substr($cpf, 0, 9);
// calculo dos 2 digitos verificadores
for($j=10; $j <= 11; $j++){
$sum = 0;
for($i=0; $i< $j-1; $i++) {
$sum += ($j-$i) * ((int) $digit[$i]);
}
$summod11 = $sum % 11;
$digit[$j-1] = $summod11 < 2 ? 0 : 11 - $summod11;
}
if($digit[9] == ((int)$cpf[9]) && $digit[10] == ((int)$cpf[10])) {
return true;
} else {
return $error;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment