Validate field of CPF

Asked

Viewed 816 times

1

I’m having trouble validating the Cpf field. In my code he is inserting Cpf in the bank always with value number 1 and returning me false, but Cpf is real. How to fix it?

code:

<?php

/*
@autor: Moacir Selínger Fernandes
@email: [email protected]
Qualquer dúvida é só mandar um email
*/

// Função que valida o CPF
function validaCPF($cpf)
{   // Verifiva se o número digitado contém todos os digitos
$cpf = str_pad(ereg_replace('[^0-9]', '', $cpf), 11, '0', STR_PAD_LEFT);

// Verifica se nenhuma das sequências abaixo foi digitada, caso seja, retorna falso
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
{   // Calcula os números para verificar se o CPF é verdadeiro
    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;
}
}

 // include do arquivo de conexão

// Adiciona o numero enviado na variavel $cpf_enviado, poderia ser outro nome, e executa a função acima
include 'conecta.php';

$nome = $_POST['nome'];
$cpf = validaCPF($_POST['cpf']);
// Verifica a resposta da função e exibe na tela
if($cpf == true){
    $sql = "INSERT INTO valida (nome ,cpf)VALUES ('$nome','$cpf')";
}
elseif($cpf == false){
echo "CPF FALSO";}
$qry = mysql_query($sql); // execultando a query

if($qry){
echo "<div class='alert alert-success' role='alert'>registro inserido com 
sucesso<meta http-equiv=refresh content='1;URL=?tag=enviarcpf.php'>";
}
mysql_close();
?>
<form action="action.php" method="post">

cpf:<input type="" value"" name="cpf">
nome:<input type="" value"" name="nome">
<input type="submit" value="enviar">
</form>
  • Just a hint/hint: Beware when exposing personal data along with the codes. In this example we see a name and an email in the code. It would be better to hide this information, or switch to *******

3 answers

4

The variable $cpf is equal to true. With this he is saving 1 in the database.

Try to separate things to do calmly. First receive the data via Post

$nome = $_POST['nome'];
$cpf = $_POST['cpf'];

Then send the data for validation:

function validarCpf($cpfParaValidar){
  $resultado = str_pad(ereg_replace('[^0-9]', '', $cpfParaValidar), 11, '0', STR_PAD_LEFT);

  return $resultado;
}

$resultado2 = validarCpf($cpf);


if($resultado2){
  //inserir no banco os dados de $cpf
} else {
  //enviar mensagem de erro para tela.
}

And then you save Cpf not the result

  • Good night I’m doing so :

  • include 'connect.php'; $name = $_POST['name']; $Cpf = validarCpf($_POST['Cpf']); Function validarCpf($cpfParaValidar){ $result = (Here you can use an Expression Language); Return $result; } $resultado2 = validarCpf($Cpf); if($resultado2){ $sql = "INSERT VALIDA (name,Cpf)VALUES ('$$name')"; } Else { echo "FALSE CPF"; } $qry = mysql_query($sql); // running query if($qry){ echo "<div class='Alert-Success' role='Alert'>entered record successfully"; } mysql_close(); ?>

  • but did not understand this part of the language expression forgive me ignorance .

  • str_pad(ereg_replace('[ 0-9]', '', $Cpf), 11, '0', STR_PAD_LEFT);

3


When you do $cpf = validaCPF($_POST['cpf']); the value of the variable $cpf is the return of the function validaCPF($_POST['cpf']); in the case of valid Cpf returns the value 1 in the variable $cpf and it is this value that will be inserted in the database in the Cpf column .

The correct is

$nome = $_POST['nome'];
$cpfTeste = validaCPF($_POST['cpf']);

// Verifica a resposta da função e exibe na tela
if($cpfTeste == true){

    $cpf=$_POST['cpf'];
    $sql = "INSERT INTO valida (nome ,cpf)VALUES ('$nome','$cpf')";
}
  • Understood friend , worked perfectly.

-2

$nome = $_POST['nome'];
$cpf = $_POST['cpf'];
$validacao = validaCPF($_POST['cpf']);

// Checks function response and displays on screen

if($validacao == true){
$sql = "INSERT INTO valida (nome ,cpf)VALUES ('$nome','$cpf')";
}elseif($validacao == false){
echo "CPF FALSO";
}

//The error was in adding the return of the function, which because it is boolean always returns 1, I added the variable $validation, it receives the return value and then is checked (in your if), so I kept your $Cpf variable intact to be inserted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.