Login screen does not validate

Asked

Viewed 104 times

0

I have a simple HTML page that contains only one login and password;

<form id="geral"  action="valida.php" method="POST" accept-charset="iso-8859-1">

            <h3><img border="0" src="financeiro/img/logo/1.png" width="80" height="70"> </h3>

            <div class="form-group-login">
                <label for="login">  </label>
                                     <input  name="login" id="login" type="text" placeholder="Digite o seu login..." />
            </div>

            <div class="form-group-login">
                <label for="password">  </label>
                    <input name="password" type="password" id="password" placeholder="Digite sua senha..." />
                         <!--<button id="btn_login" class="botao">Entrar</button> -->
                          <button  type="submit" id="enviar" value="enviar" class="botao" >Entrar</button>




        </form>

After entering Login and password, it is directed to a file called valida.php. In this file, just refer to another file called.php security, whose file does all the security analysis to log in or not.

valida.php

valida.php

    //Inclui o arquivo com o sistema de segurança
require_once("seguranca.php");

//Verifica se um formulário foi enviado
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    //Salva duas variáveis com o que foi digitado no formulário
    //Detalhe: faz uma verificação com isset() pra saber se o campo foi preenchido
    $usuario = (isset($_POST['login'])) ? $_POST['login'] : '';
    $senha = (isset($_POST['password'])) ? $_POST['password'] : '';

    //Utiliza uma função criada no seguranca.php para validar os dados digitados
    if (validaUsuario($usuario, $senha) == true) {
        // O usuário e a senha digitados foram validados, manda pra pagina interna
        header("Location: /financeiro/index.html");
    }else {
     // O usuário e/ou a senha são inválidos, manda de volta pro form de login
     // Para alterar o endereço da pagina de login, verifique o arquivo 





    expulsaVisitante();
        }
    }

php security.

Seguranca.php

    function validaUsuario($usuario, $senha) {
global $_SG;
//$cS = ($_SG['caseSensitive']) ? 'BINARY' : '';
// Usa a função addslashes para escapar as aspas
//$nusuario = addslashes($usuario);
//$nsenha = addslashes($senha);
//$senhamd5 = md5($nsenha);
// Monta uma consulta SQL (query) para procurar um usuário

$sql = "SELECT `id`, `nome` FROM usuario` WHERE  `usuario` = '$usuario' AND `senha` = '$senha' LIMIT 1";
$query = mysqli_query($conexao, $sql);
$resultado = mysqli_fetch_assoc($query);

// Verifica se encontrou algum registro
if ($resultado) {


// Definimos dois valores na sessão com os dados do usuário
$_SESSION['usuarioID'] = $resultado['id']; // Pega o valor da coluna 'id do registro encontrado no MySQL
$_SESSION['usuarioNome'] = $resultado['nome']; // Pega o valor da coluna 'nome' do registro encontrado no MySQL

// Verifica a opção se sempre validar o login
if ($_SG['validaSempre'] == true) {

// Definimos dois valores na sessão com os dados do login
$_SESSION['usuarioLogin'] = $usuario;
$_SESSION['usuarioSenha'] = $senha;
}
return true;


// Nenhum registro foi encontrado => o usuário é inválido


} else {

 return false;

  }
}

The problem is that by putting right or wrong data it does not allow logging in. It always falls in Returne false, from IF in the User Validator function. If you test by putting if (isset($result)), it lets you log in with right or wrong data.

Debugging the code, I echo the variables and the error is this:

 Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\dashboard\web\web\seguranca.php on line 55
SELECT id, nome FROM usuario WHERE usuario = 'teste' AND senha = '123mudar' LIMIT 1

If I play this select directly via terminal brings me the column with this data, however searching says the error is in Query.

  • if you echo $user and $password before query select, what returns? , the data is coming?

  • I did a test, commenting on the line that falls in the role of Expulsausuario and I put an echo as you asked and in fact is not getting anything.

  • friend you are forgetting to start Session do session_start(); @user54154

  • In the.php security file, at the beginning of the code I have session_start();, is that I did not put this excerpt here.

  • starts Session there inside the file that validates

  • I put session_start(); at the beginning of valida.php and tb does not take the variables.

  • Take all `out of the query. When you call a table field you do not need to put this.

  • You don’t need this LIMIT 1, since you just want to know if the registration in question "exists" or "no".

  • I had already done this test to remove LIMIT and `, but same error mysqli_fetch_assoc() expects Exactly 1 Parameter, 2 Given in

Show 4 more comments

1 answer

0


The first very important thing you have to take into account is that all functions (mysql_* and mysqli_*) are obsolete and since php version 7 have already been removed.

The second thing is when you are working with any type of parameter being passed within sql, you should never put the variables inside simple quotes '', ex. "select * from table Where id='$id'", this causes a problem because php will interpret its variable as a string, to avoid this its instruction should be as follows: "select * from table Where id={$id}" or "select * from table Where id=$id".

What your consultation should look like:

$sql = "SELECT `id`, `nome` FROM usuario` WHERE  `usuario` = {$usuario} AND `senha` = {$senha} LIMIT 1";

or...

 $sql = "SELECT `id`, `nome` FROM usuario` WHERE  `usuario` = ".$usuario." AND `senha` = ".$senha." LIMIT 1";

Example with delimiters \"\"

$sql = "SELECT `id`, `nome` FROM usuario` WHERE  `usuario` = \"".$usuario."\" AND `senha` = \"".$senha."\" LIMIT 1";

To work with a database you must use the class PDO php native.

To help you understand better I’ll help you with a simple example working with this class.

Connection:

//Iniciamos a instância do objeto PDO
//e passamos no último parâmetro o tipo de caracteres
//que vamos trabalhar sendo tipo utf-8
$pdo = new PDO('mysql:host=seulocalhost;dbname=seubanco', 'seuuser', 'suasenha', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8"));

//Definimos para que o PDO lance exceções em casos de erro
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

SQL statement for simple query:

// executa a instrução SQL
$consulta = $pdo->query("SELECT nome, senha FROM table_users");

Simple SQL statement with parameter passing:

//prepara a instrução SQL utilizando o método "prepare()"
$consulta = $pdo->prepare("SELECT email, senha FROM table_users WHERE email=:email AND senha=:senha");


//Define os padrões de tipos de parâmetros em que a instrução deverá trabalhar
$consulta->bindValue(':email', '[email protected]', PDO::PARAM_STR); //define para o mysql que este parâmetro deverá ser somente string
$consulta->bindValue(':senha', 'sample2017', PDO::PARAM_STR); //define para o mysql que este parâmetro deverá ser somente string
$consulta->execute(); //executa a query

Conta Registros

if($consulta->rowCount() >= 1){
    //code...
}

Traversing data

foreach($consulta->fetchAll(PDO::FETCH_OBJ) as $item) {
    echo $item->email;
}
  • Very good Rafael, I will study your tips for my learning. I ended up solving this case in another way, using the PDO and adjusting my SQL as your tips above. Grateful

  • We are all always learning and looking for the best, I’m glad you took advantage of all this, abs!

Browser other questions tagged

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