Skip to content

Instantly share code, notes, and snippets.

@YurePereira
Last active June 3, 2025 15:00
Show Gist options
  • Select an option

  • Save YurePereira/3e402feb49423559035a40cf31023b3c to your computer and use it in GitHub Desktop.

Select an option

Save YurePereira/3e402feb49423559035a40cf31023b3c to your computer and use it in GitHub Desktop.
Validate CPF in PHP (Validar CPF em PHP).
<?php
/**
*
* Função que faz a validação de CPF, verificando se ele está no formato certo, exemplo 'xxx.xxx.xxx-xx' ou 'xxxxxxxxxxx', e se
* ele é válido, caso as duas verificação sejam verdadeiras será retornado TRUE ou FALSE caso contrario.
*
* @param c: String CNPJ a se validado.
* @return Boolean
*
*/
function validCPF($c) {
if (preg_match('/^[0-9]{3}\.?[0-9]{3}\.?[0-9]{3}\-?[0-9]{2}$/', $c)) {
$c = preg_replace('/(\.|\-)/g', '', $c);
$s = 0;
$i = 0;
$i2 = 0;
$j = 0;
$cpf = [];
for ($i = 0; $i <= 8; $i++) {
$cpf[$i] = $c[$i];
}
for ($i = 10; $i >= 2; $i--) {
$s += $cpf[$j] * $i;
$j += 1;
}
$cpf[9] = ($s % 11 > 2) ? 11 - ($s % 11) : 0;
$s = 0;
$j = 0;
for ($i = 11; $i >= 2; $i--) {
$s += $cpf[$j] * $i;
$j += 1;
}
$cpf[10] = ($s % 11 > 2) ? 11 - ($s % 11) : 0;
$s = 0;
$j = 0;
return $cpf[9] == $c[strlen($c) - 2] && $cpf[10] == $c[strlen($c) - 1];
} else {
return false;
}
}
//Testing validation.
$cpf = '23758508231';//CPF random.
if (validCPF($cpf)) {
echo 'CPF is valid!';
} else {
echo 'CPF is not valid!';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment