Last active
March 26, 2019 16:05
-
-
Save lenivene/74d4b951cdf0a81015f4c7e3d480c029 to your computer and use it in GitHub Desktop.
Verificar se o CPF ( Cadastro de pessoas físicas ) é um número valido. - Via: PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Verificar se o CPF ( Cadastro de pessoas físicas ) é um número valido. | |
* | |
* @author Lenvene Bezerra | |
* @return true | false | |
*/ | |
function is_cpf( $cpf ){ | |
if( ! isset( $cpf ) || isset( $cpf ) && empty( $cpf ) ) | |
return false; | |
// Retorna só os números | |
$cpf = preg_replace( '/[^0-9]/', '', $cpf ); | |
/** | |
* CPF tem 11 digitos, verifica se não é 11. | |
* Verifica se foi informada uma sequência de digitos repetidos. | |
*/ | |
if( mb_strlen( $cpf ) != 11 || preg_match('/(\d)\1{10}/', $cpf ) ) | |
return false; | |
/** | |
* Calculo para validar o CPF | |
*/ | |
for( $t = 9; $t < 11; $t++ ){ | |
for( $d = 0, $c = 0; $c < $t; $c++ ){ | |
$d += $cpf{$c} * ( ( $t + 1 ) - $c ); | |
} | |
$d = ( ( 10 * $d) % 11 ) % 10; | |
if ( $cpf{$c} != $d ) | |
return false; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment