Advertisement
Guest User

Validador de cpf

a guest
Sep 17th, 2019
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. <?php
  2. class ValidaCpf
  3. {
  4. protected function pegaDigito($digitos, $posicoes = 10, $somadigitos = 0)
  5. {
  6. $arrayDigitos = str_split($digitos,1);
  7.  
  8. for ($i = 0; $i < strlen($digitos); $i ++ )
  9. {
  10. $somadigitos = $somadigitos + ($arrayDigitos[$i] * $posicoes);
  11. $posicoes--;
  12. }
  13. $somadigitos = $somadigitos % 11;
  14. if ($somadigitos < 2) {
  15. $novocpf = $digitos . '0';
  16. } else {
  17. $somadigitos = 11 - $somadigitos;
  18. $novocpf = $digitos.$somadigitos;
  19. }
  20. return $novocpf;
  21. }
  22.  
  23. protected function valida($cpf = false)
  24. {
  25. if (!$cpf)
  26. {
  27. return false;
  28. } else {
  29. $cpf = preg_replace('/[^0-9]/is', '', $cpf);
  30. if (strlen($cpf) != 11) {
  31. return false;
  32. } else {
  33. $primeirosDigitos = substr($cpf, 0 ,9);
  34. $novo = $this->pegaDigito($primeirosDigitos);
  35. $novo = $this->pegaDigito($novo, 11);
  36. if ($cpf === $novo) {
  37. return true;
  38. } else {
  39. return false;
  40. }
  41. }
  42. }
  43. }
  44.  
  45. public function retornaCpf($cpf){
  46. return $this->valida($cpf);
  47. }
  48. }
  49.  
  50. ?>
  51.  
  52.  
  53. <html>
  54. <head>
  55. <title>Valida Cpf</title>
  56. </head>
  57.  
  58. <body>
  59. <form action="#" method="post">
  60. <label for="cpf"></label>
  61. <input type="text" id="cpf" name="cpf">
  62. <input type="submit" value="enviar">
  63. </form>
  64. </body>
  65. </html>
  66. <?php
  67. require_once('classCpf.php');
  68. $cpf = $_POST['cpf'];
  69.  
  70. $validarcpf = new ValidaCpf;
  71. if($validarcpf->retornaCpf($cpf))
  72. {
  73. echo "Cpf valido";
  74. } else {
  75. echo "Cpf invalido";
  76. }
  77. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement