Login panel does not return the number of accounts

4

I'm creating a login area, but when I click the login button, it does not return any errors, for example: if the user does not exist I would like the number 0 to appear as the $num variable, however a screen page.

PHP :     

    $conn = mysqli_connect($servidor, $usuario, $senha, $dbname) or die(mysqli_error());


    if (isset($_POST['email']) && isset($_POST['senha'])) {

      $email = $_POST['email'];
      $senha = $_POST['senha'];

      $get = mysqli_query($conn, "SELECT * FROM  usuarios WHERE email = '$email' AND senha = '$senha'");
      $num = mysqli_num_rows($get);

          echo $num;
    }
?>

HTML :

<!DOCTYPE html>
<html lang="pt" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Painel Admin Login</title>
    </head>
    <body>
        <form action="login.php" method="post">
            <input type="text" name="usuario" placeholder="Usuário"><br>
            <input type="password" name="senha" placeholder="Senha"><br>
            <input type="submit" value="Login">
        </form>
    </body>
</html>
    
asked by anonymous 12.12.2018 / 23:41

2 answers

2
  

but a blank screen appears on the page

Very likely to fall into this condition:

if (isset($_POST['email']) && isset($_POST['senha'])) {
  

I'm a beginner, and I did not quite understand what you said.

The code expects that the values of post and email be passed via senha . If it does not, it skips the entire block, which in fact lacks this condition ( } ).

In order to test, you can place a counter condition in your code. It would look something like this:

if (isset($_POST['email']) && isset($_POST['senha'])) {

  $email = $_POST['email'];
  $senha = $_POST['senha'];

  $get = mysqli_query($conn, "SELECT * FROM  usuarios WHERE email = '$email' AND senha = '$senha'");
  $num = mysqli_num_rows($get);

      echo $num;

} else echo "e-Mail e/ou senha não informados!";

This way, your page should display the message if you did not pass the values of email and senha .

@edit:

Notice that your HTML has these input :

<input type="text" name="usuario" placeholder="Usuário"><br>
<input type="password" name="senha" placeholder="Senha"><br>

And in the PHP script you are getting these variables:

//...
// Aqui deveria ser "usuario" ao invés de "email"
if (isset($_POST['email']) && isset($_POST['senha'])) {
    //...
    $email = $_POST['email']; // Aqui deveria ser "usuario"
    $senha = $_POST['senha'];
    //...

The name attributes of the form must be compatible with the keys found in the $_POST variable.

@ edit2:

Finally, the code concludes as follows:

login.php:

<?php
    if(session_status() !== PHP_SESSION_ACTIVE) session_start();

        $dbInfo = array(
        'host' => 'localhost',
        'usuario' => 'root',
        'senha' => '',
        'db' => 'login'
    );

    $conn = mysqli_connect($dbInfo['host'], $dbInfo['usuario'], $dbInfo['senha'], $dbInfo['db']) or die(mysqli_error());

    if (isset($_POST['usuario']) && $_POST['usuario'] != '' && strlen($_POST['usuario']) >= 4 && isset($_POST['senha']) && $_POST['senha'] != '') {

        $usuario = $_POST['usuario'];
        $senha = $_POST['senha'];

        if(!($get = mysqli_query($conn, "SELECT * FROM  usuarios WHERE nome = '$usuario' AND senha = '$senha';"))){
            echo "Erro na consulta: ".mysqli_error($conn);
            die(); // Para toda a execução do código.
        }
        if(mysqli_num_rows($get) == 1) {
            $_SESSION['logado'] = true;
            echo "Login efetuado com sucesso!";
        } else {
            echo "Falha ao efetuar o login";
        }

    } else echo "Usuário e/ou senha não informados.";

    // Logout:
    //unset($_SESSION['logado']);

?>

index.php:

<!DOCTYPE html>
<html lang="pt" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Painel Admin Login</title>
    </head>
    <body>
        <form action="login.php" method="post">
            <input type="text" name="usuario" placeholder="Usuário" required="required" minlength="4"><br>
            <input type="password" name="senha" placeholder="Senha" required="required"><br>
            <input type="submit" value="Login">
        </form>
    </body>
</html>

Database structure (MariaDB):

+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| nome  | varchar(100) | NO   |     | NULL    |                |
| senha | varchar(100) | NO   |     | NULL    |                |
| adm   | int(10)      | NO   |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
    
12.12.2018 / 23:51
1

If in PHP it is isset($_POST['email'] then in HTML it should be <input type="text" name="email" placeholder="email"> which is the most suggestive.

Now nothing prevents HTML from being <input type="text" name="usuario" placeholder="Usuário"> but in PHP it should be isset($_POST['usuario']

The only error in your code is this. See your working code functional example Existing login [email protected] password ABCD returns 1 to any other return 0

<?php

$conn = mysqli_connect("localhost","USUARIO","SENHA",Nome_DB");

if (isset($_POST['email']) && isset($_POST['senha'])) {

  $email = $_POST['email'];
  $senha = $_POST['senha'];

  $get = mysqli_query($conn, "SELECT * FROM  usuarios WHERE email = '$email' AND senha = '$senha'");
  $num = mysqli_num_rows($get);

      echo $num;
}
 ?>

 <!DOCTYPE html>
<html lang="pt" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Painel Admin Login</title>
    </head>
    <body>
        <form action="" method="post">
            <input type="text" name="email" placeholder="email"><br>
            <input type="password" name="senha" placeholder="Senha"><br>
            <input type="submit" value="Login">
        </form>
    </body>
</html>
  

As you can see, you did not just want to know what the error was in your question, which had been given in my already deleted comment. I'll post a complete and secure response so that you have a good learning experience.

1 - Be careful when constructing your SELECT statement, because the more data that is read from the tables, the longer it will take to execute. Especially when the database server is separate from the application server, because the data will have to pass through the network between the two.

Make it a habit to always specify the columns you'll need when assembling your SELECT.

2 - <input type="email"> validates the field to ensure the typed data is actually a valid email address.

3 - required is a Boolean attribute used to indicate that a determining form field is required to send it. When you add this attribute to a form field, the browser forces the user to enter data in that field before submitting the form.

4 - Avoid SQL Injection using Prepared Statements in PHP.

One of the biggest vulnerabilities of websites, SQL injection is also, in the case of PHP, one of the easiest to prevent. Unfortunately, many do not take the necessary precautions and end up having their data compromised.

In the example I'm going to use prepared statements using PHP PDO extension

  

In PHP, the MySQLi extension also supports prepared statements, but it is better to use the PDO as it facilitates migration to other banks, as well as offering a concise API between them.

Functional sample

<?php

$servername = "localhost";
$username = "USUARIO";
$password = "SENHA";
$dbname = "Nome_DB";


if(isset($_POST['submit'])){

    if ( (isset($_POST['email']) && !empty($_POST['email'])) &&  (isset($_POST['senha']) && !empty($_POST['senha'])) ) {

      $email = $_POST['email'];
      $senha = $_POST['senha'];

        try{
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
            // define o modo de erro do PDO para exceção
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


            $stmt = $conn->prepare("SELECT email, senha FROM usuarios WHERE email= :email and senha = :senha");
             $stmt->bindParam(':email', $email,  PDO::PARAM_STR);
             $stmt->bindParam(':senha', $senha,  PDO::PARAM_STR);
             $stmt->execute();

             $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

             $count =  count($users);

                echo $count;    

        }

            catch(PDOException $e)
            {
            echo $sql . "<br>" . $e->getMessage();
            }

        $conn = null;

    }else{
        echo "Os dois campos são obrigatorios";
    }

}

?>

<!DOCTYPE html>
<html lang="pt" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Painel Admin Login</title>
    </head>
    <body>
        <form action="" method="post">
            <input type="email" name="email" placeholder="email" required><br>
            <input type="password" name="senha" placeholder="Senha" required><br>
            <input type="submit" value="Login" name="submit">
        </form>
    </body>
</html>

5 - Why client side (front-end) and server-side (back-end) validation

Validating data being sent by the user only in javascript is not enough because of:

  • If the user disables javascript, you may end up with invalid data on the server

  • Because the front end is accessible in the browser. And all the code that is there, can end up being changed by someone who has advanced knowledge and bad intentions. The JavaScript code can be perfectly changed and thus validation can be circumvented.

  • Server validations make a site less susceptible to malicious robots

In summary ... it's worth cautioning against all these unknown agents, doing the validation on the server (which is the most trusted agent) as being the main ... and in javascript, as a validator, by you do not need to go to the server.

6 - - The try / catch block is used to handle exceptions, handling of codes that may not be fully met and generate some exception / error.

The try is able to recover errors that may occur in the code provided in your block. The catch in turn treats the errors that have occurred.

Should be used preferably when the developer can not guarantee that the code will run successfully.

    
13.12.2018 / 01:29