Skip to content

Instantly share code, notes, and snippets.

@othonet
Created April 14, 2022 15:09
Show Gist options
  • Save othonet/9b3f6b9c391e46c95c7841bc4f56fb66 to your computer and use it in GitHub Desktop.
Save othonet/9b3f6b9c391e46c95c7841bc4f56fb66 to your computer and use it in GitHub Desktop.
PHP - Validate CPF Format
<?php
function isCPFValido($valor){
$valor = str_replace(array('.','-','/'), "", $valor);
$cpf = str_pad(preg_replace('[^0-9]', '', $valor), 11, '0', STR_PAD_LEFT);
if (strlen($cpf) != 11 || $cpf == '00000000000' || $cpf == '11111111111' || $cpf == '22222222222' || $cpf == '33333333333' || $cpf == '44444444444' || $cpf == '55555555555' || $cpf == '66666666666' || $cpf == '77777777777' || $cpf == '88888888888' || $cpf == '99999999999'):
return false;
else:
for ($t = 9; $t < 11; $t++):
for ($d = 0, $c = 0; $c < $t; $c++) :
$d += $cpf{$c} * (($t + 1) - $c);
endfor;
$d = ((10 * $d) % 11) % 10;
if ($cpf{$c} != $d):
return false;
endif;
endfor;
return true;
endif;
}
$valor = '34291199287';
if(isCPFValido($valor)):
echo 'CPF válido.';
else:
echo 'CPF inválido.';
endif;
// Saída CPF válido
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment