Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class ValidaCpf
- {
- protected function pegaDigito($digitos, $posicoes = 10, $somadigitos = 0)
- {
- $arrayDigitos = str_split($digitos,1);
- for ($i = 0; $i < strlen($digitos); $i ++ )
- {
- $somadigitos = $somadigitos + ($arrayDigitos[$i] * $posicoes);
- $posicoes--;
- }
- $somadigitos = $somadigitos % 11;
- if ($somadigitos < 2) {
- $novocpf = $digitos . '0';
- } else {
- $somadigitos = 11 - $somadigitos;
- $novocpf = $digitos.$somadigitos;
- }
- return $novocpf;
- }
- protected function valida($cpf = false)
- {
- if (!$cpf)
- {
- return false;
- } else {
- $cpf = preg_replace('/[^0-9]/is', '', $cpf);
- if (strlen($cpf) != 11) {
- return false;
- } else {
- $primeirosDigitos = substr($cpf, 0 ,9);
- $novo = $this->pegaDigito($primeirosDigitos);
- $novo = $this->pegaDigito($novo, 11);
- if ($cpf === $novo) {
- return true;
- } else {
- return false;
- }
- }
- }
- }
- public function retornaCpf($cpf){
- return $this->valida($cpf);
- }
- }
- ?>
- <html>
- <head>
- <title>Valida Cpf</title>
- </head>
- <body>
- <form action="#" method="post">
- <label for="cpf"></label>
- <input type="text" id="cpf" name="cpf">
- <input type="submit" value="enviar">
- </form>
- </body>
- </html>
- <?php
- require_once('classCpf.php');
- $cpf = $_POST['cpf'];
- $validarcpf = new ValidaCpf;
- if($validarcpf->retornaCpf($cpf))
- {
- echo "Cpf valido";
- } else {
- echo "Cpf invalido";
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement