Login with validation system

Asked

Viewed 529 times

1

In my system login, if the user has registered id and password the access is released. So far so good, but now I want to qualify this user in administrator(1) or simple user(0) to, when they log in, be redirected to different pages.

For that, I created a column "ativo" to store the 0 or 1 in my user table and started writing a validation page that is not working yet:

<?php

// Primeiro verifica se o post não está vazio
if (!empty($_POST) AND !empty($_POST['identifiant']) OR !empty($_POST['senha'])) {
    mysql_connect('localhost', 'root', '', 'db_formacao') or trigger_error(mysql_error());
    // Tenta se conectar a um banco de dados MySQL
    $identifiant = mysql_real_escape_string($_POST['identifiant']);
    $senha = mysql_real_escape_string($_POST['senha']);
    $ativo = mysql_real_escape_string($_POST['ativo']);

    $sql = "SELECT `id`, `identifiant`, `senha`, `ativo`  FROM `usuarios` WHERE (`identifiant` = '". $identifiant ."') AND (`senha` = '". $senha ."')";
    $query = mysql_query($sql);
    if (mysql_num_rows($query) != 1) {
      // Mensagem de erro quando os dados são inválidos e/ou o usuário não foi encontrado
      echo "Login inválido!"; exit;
    } else {
      $resultado = mysql_fetch_assoc($query);
      // Verifica se o usuário é 0 ou 1

      if ($resultado['ativo'] == 0)) { header("Location: principalUSU.php"); } 
      else { header("Location: principal.php"); }

      exit;
    }
}
?>

The login page is where the login form is and the action that connects with the validation page:

<!--CONTENT-->
    <!--A parte do formulário-->
    <div class="container">
        <div class="row">
            <div class="col-md-4 col-md-offset-4">
                <div class="login-panel panel panel-default">
                    <div class="panel-heading" style="
    margin-top: 14px;">
                        <h3 class="panel-title">Login</h3>
                    </div>
                    <div class="panel-body" style="background: rgba(32, 40, 76, 0.59);">
                        <?php 
                        if(isset($erro)) 
                            if(count($erro) > 0){ ?>
                                <div class="alert alert-danger">
                                    <?php foreach($erro as $msg) echo "$msg <br>"; ?>
                                </div>
                            <?php 
                            }
                            ?>
                        <form method="post" action="validacao.php" role="form">
                            <fieldset style="background: #9498a9;">
                                <div class="form-group">
                                    <input  class="form-control" placeholder="Identifiant" name="identifiant">
                                </div>
                                <div class="form-group">
                                    <input class="form-control" required placeholder="Senha" name="senha" type="password" value="">
                                </div>
                                <div class="checkbox">
                                    <label>
                                        <input name="remember" type="checkbox" value="Remember Me">Lembrar-me
                                    </label>
                                </div>

                                <button type="submit" name="login" value="true" class="btn btn-success btn-block" style="background: #232b4f; border-color: #e2e2e2;">Login</button>
                            </fieldset>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

The table as in the database:

id  |  nome  |  senha  |  ativo  
 1     aaaa     12345       1
 2     bbbb     12345       0 

But when I try to turn the page erro 500 saying the page isn’t working. Any idea why it doesn’t work?

BS: I changed my code to what appears here in the answer, but is still giving error 500.

3 answers

3

Try it like this:

<?php

// Primeiro verifica se o post não está vazio
if (!empty($_POST) AND !empty($_POST['identifiant']) OR !empty($_POST['senha'])) {
    $conexao = mysqli_connect('localhost', 'root', '', 'db_formacao') or trigger_error(mysqli_error($conexao));
    // Tenta se conectar a um banco de dados MySQL
    $identifiant = mysqli_real_escape_string($conexao, $_POST['identifiant']);
    $senha = mysqli_real_escape_string($conexao,$_POST['senha']);
    $ativo = mysqli_real_escape_string($conexao,$_POST['ativo']);

    $sql = "SELECT `id`, `identifiant`, `senha`, `ativo`  FROM `usuarios` WHERE (`identifiant` = '". $identifiant ."') AND (`senha` = '". $senha ."')";
    $query = mysqli_query($sql);
    if (mysqli_num_rows($query) != 1) {
      // Mensagem de erro quando os dados são inválidos e/ou o usuário não foi encontrado
      echo "Login inválido!"; exit;
    } else {
      $resultado = mysqli_fetch_assoc($query);
      // Verifica se o usuário é 0 ou 1

      if ($resultado['ativo'] == 0)) { header("Location: principalUSU.php"); } 
      else { header("Location: principal.php"); }

      exit;
    }
}
?>
  • 1

    To learn more about PHP and login security, I suggest this channel: https://www.youtube.com/watch?v=rCrf70u7hFI

  • Thank you for answering! I copied your code, but it still gives error 500 when it falls on the validation page. It might be on the login page?

2


You have problem in the first if / Else, where you try to find the type of active variable before making the SQL query, the line below is wrong:

(`ativo` = 1)

It is not a variable and tbm does not use this type of accent outside the mysql query.

You have to make the query in the database first to then identify the type of user and then yes open the page accordingly.

something like this:

<?php

// Primeiro verifica se o post não está vazio, coloque um sinal ! de negação para verificar se identifiant ou senha também não estão vazios.
if (!empty($_POST) AND !empty($_POST['identifiant']) OR !empty($_POST['senha'])) {
  // Caso esteja preenchidos, vamos seguir com o codigo abaixo
    mysql_connect('localhost', 'root', '', 'db_formacao') or trigger_error(mysql_error());
    // Tenta se conectar a um banco de dados MySQL
    $identifiant = mysql_real_escape_string($_POST['identifiant']);
    $senha = mysql_real_escape_string($_POST['senha']);
    $ativo = mysql_real_escape_string($_POST['ativo']);

    // Na linha abaixo não coloque o (`ativo` = '". $ativo ."'), pq é essa informação que vc quer retornar para verificar o tipo de usuário.
    $sql = "SELECT `id`, `identifiant`, `senha`, `ativo`  FROM `usuarios` WHERE (`identifiant` = '". $identifiant ."') AND (`senha` = '". $senha ."')";
    $query = mysql_query($sql);
    if (mysql_num_rows($query) != 1) {
      // Mensagem de erro quando os dados são inválidos e/ou o usuário não foi encontrado
      echo "Login inválido!"; exit;
    } else {
      $resultado = mysql_fetch_assoc($query);
      // Agora sim, vc tem o resultado do banco de dados, é aqui q vc vai verificar se o seu usuário é ativo 0 ou 1;

      if ($resultado['ativo'] == 0)) { header("Location: principalUSU.php"); } 
      else { header("Location: principal.php"); }

      exit;
    }
}
?>

Now just two tips...

1) Try to learn about Mysqli, because the Mysql code is old, and many servers no longer use it.

2) If your system contains very confidential information, I suggest you try to search better about login security, because your method is very simple, and easy to hack.

I hope I helped. Hugs

  • Ah, great explanation, makes much more sense now, thanks for the tips; I tried to use your code now but still gives the error 500. Do you know if it can be on the other page or in the database? (I’ll even edit my question and put your code)

  • 1

    Hello Mariana. Try to exchange mysql for mysqi as Fernando mentioned, because as many servers no longer use, this may be generating conflicts.

  • 1

    Just to try to help a little. http://phpcodechecker.com Helps identify wrong parentheses and syntax errors. Paste your php codes there and have them check that it shows a list of warnings and errors.

  • Wow, that was really helpful, just today I was wondering if there was such a thing

  • must be giving error 500 on account of an error in the code, by which I saw over that line if ($resultado['ativo'] == 0)) { header... is with a more parenthesis, I had not tested his code, I just answered reading q is written, but tries to correct this part by taking one of the parentheses, getting like this: if ($resultado['ativo'] == 0) { header.... I believe that’s it.

  • 2

    The suggestion of Fox.11’s response by converting to mysqli can help you a lot. But I suggest you take a look at the php documentation to better understand how it works and know what you’re doing with your code. Avoid just copy and paste, so you will have more difficulties learning.

  • It worked, Fernando! It was the parenthesis, I’m embarrassed. kkkkk Thank you very much.

  • kkkk q good q worked @Marianaferreira, don’t be embarrassed, it happens to everyone more often than q vc imagine kkkk hugs.

Show 3 more comments

1

Error 500 is programming problem, in which case you should consult apache log to see the error messages or enable the display of them only in the script with the lines, are put at the beginning.

ini_set('display_errors', true);
error_reporting(E_ALL);

How you are using old mysql_functions (which have already been removed from php7). The problem seems to be in connection, it is not possible to pass the name of the bank as the fourth argument correct only for the functions mysql_* is to call mysql_select_db()

Change:

 mysql_connect('localhost', 'root', '', 'db_formacao') or trigger_error(mysql_error());

To:

 $link = mysql_connect('localhost', 'root', '');
 mysql_select_db('db_formacao');

Another detail, take care of the operators && and AND, || and OR are not synonymous.

Related:

Qual a diferença entre “&&” e “||” e “and” e “or” em PHP? Qual usar?

  • Thanks for answering! I changed the connection as suggested, but it’s still giving the same error 500. it is strange that all the answers keep giving the same error on the validation page. Could it be on the form page the problem?

  • @Marianaferreira even with the ini_set didn’t show errors? looked at apache log?

  • Ah, it was my mistake. It was an extra parenthesis. I’m sorry.

Browser other questions tagged

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