Explanation of login and profile validation code

Asked

Viewed 1,275 times

2

I’m learning php however (I don’t know if it’s the custom of a beginner) the code is getting messy as I try new things. I took some lessons on youtube channel Celke however despite being very didactic sometimes seems to me some things unnecessary when comparing with other codes.. And in the following code I’m having trouble organizing, someone could help me explain it?

The following code validates login valida.php

<?php
session_start();
//Incluindo a conexão com banco de dados
include_once("conexao.php");
//O campo usuário e senha preenchido entra no if para validar
if((isset($_POST['email'])) && (isset($_POST['senha']))){
    $usuario = mysqli_real_escape_string($conn, $_POST['email']); //Escapar de caracteres especiais, como aspas, prevenindo SQL injection
    $senha = mysqli_real_escape_string($conn, $_POST['senha']);
    $senha = md5($senha);

    //Buscar na tabela usuario o usuário que corresponde com os dados digitado no formulário
    $result_usuario = "SELECT * FROM usuarios WHERE email = '$usuario' && senha = '$senha' LIMIT 1";
    $resultado_usuario = mysqli_query($conn, $result_usuario);
    $resultado = mysqli_fetch_assoc($resultado_usuario);

    //Encontrado um usuario na tabela usuário com os mesmos dados digitado no formulário
    if(isset($resultado)){
        $_SESSION['usuarioId'] = $resultado['id'];
        $_SESSION['usuarioNome'] = $resultado['nome'];
        $_SESSION['usuarioNiveisAcessoId'] = $resultado['niveis_acesso_id'];
        $_SESSION['usuarioEmail'] = $resultado['email'];
        $_SESSION['usuarioEndereco'] = $resultado['endereco'];
        if($_SESSION['usuarioNiveisAcessoId'] == "1"){
            header("Location: administrativo.php");
        }elseif($_SESSION['usuarioNiveisAcessoId'] == "2"){
            header("Location: colaborador.php");
        }else{
            header("Location: cliente.php");
        }
    //Não foi encontrado um usuario na tabela usuário com os mesmos dados digitado no formulário
    //redireciona o usuario para a página de login
    }else{
        //Váriavel global recebendo a mensagem de erro
        $_SESSION['loginErro'] = "Usuário ou senha Inválido";
        header("Location: index.php");
    }
//O campo usuário e senha não preenchido entra no else e redireciona o usuário para a página de login
}else{
    $_SESSION['loginErro'] = "Usuário ou senha inválido";
    header("Location: index.php");
}?>

And the user page php client.

<?php
 include_once("conexao.php");

session_start();
if (isset($_SESSION['usuarioId'])) {
    $usuarioid = $_SESSION['usuarioId'];
    $nome_perfil = $_SESSION['usuarioNome'];
}


?>

I don’t know if it’s too much to ask, however someone could wipe this valida.php code and help me with the.php client page so I can enter db information in it, i want to dispose of the registrations performed by users however do not know how to get the user id along with session_start. *I think the explanation of my problem was as confusing as the same.

  • 2

    Throw away this code, and search the site for something based on password_hash and password_verify. This whole select-password thing doesn’t make sense. In addition, concatenating string to mount SQL is another bizarre thing, searching for SQL Injection and the function mysqli_bind_param to merge in a slightly safer way. Other than that, I don’t usually recommend using this technique to keep redirecting, but if it is to do, always remember to die(); after redirecting to have no side effects (at least until you have a real reason to leave the script running).

  • That one md5($senha) summarizes your code, this has been broken since 1994, if you are learning then use recent and currently safe technologies like Bcrypt and Argon2, the first is supported by password_hash(). Use SELECT * tends to be slower, moreover it is not clear what you get if you do something like SELECT id, nome FROM ... It is clear that you get these two columns, without having to navigate the rest of the code. Another problem is not having minimum number of characters in the password, including empty passwords will be valid. About the organization, I don’t see many problems.

2 answers

2

There are reasons why you may think there are unnecessary things there, but it would also be right to think that necessary things are missing.

You could do it like this:

<?php
session_start();
//Incluindo a conexão com banco de dados
include_once("conexao.php");
//O campo usuário e senha preenchido entra no if para validar
if((isset($_POST['email'])) && (isset($_POST['senha']))){
    $usuario = mysqli_real_escape_string($conn, $_POST['email']); //Escapar de caracteres especiais, como aspas, prevenindo SQL injection
    $senha = mysqli_real_escape_string($conn, $_POST['senha']);
    $senha = md5($senha);

    //Buscar na tabela usuario o id e nivel que corresponde com os dados digitado no formulário
    $result_usuario = "SELECT id, niveis_acesso_id FROM usuarios WHERE email = '$usuario' && senha = '$senha' LIMIT 1";
    $resultado_usuario = mysqli_query($conn, $result_usuario);
    $resultado = mysqli_fetch_assoc($resultado_usuario);

    //Encontrado um usuario na tabela usuário com os mesmos dados digitado no formulário
    if(isset($resultado)){
        $_SESSION['usuarioId'] = $resultado['id'];
        $_SESSION['usuarioNiveisAcessoId'] = $resultado['niveis_acesso_id'];
        if($_SESSION['usuarioNiveisAcessoId'] == "1"){
            header("Location: administrativo.php");
            exit;
        }elseif($_SESSION['usuarioNiveisAcessoId'] == "2"){
            header("Location: colaborador.php");
            exit;
        }else{
            header("Location: cliente.php");
            exit;
        }
    //Não foi encontrado um usuario na tabela usuário com os mesmos dados digitado no formulário
    //redireciona o usuario para a página de login
    }else{
        //Váriavel global recebendo a mensagem de erro
        $_SESSION['loginErro'] = "Usuário ou senha Inválido";
        header("Location: index.php");
        exit;
    }
//O campo usuário e senha não preenchido entra no else e redireciona o usuário para a página de login
}else{
    $_SESSION['loginErro'] = "Usuário ou senha inválido";
    header("Location: index.php");
    exit;
}

example using Prepared statements: Pastebin

Read this too: How best to create a login system with php ?

Instead of selecting all user-related columns, simply select the id and the nivel of that user, and on the page client you check the id of that user and returns the information from there. And whenever you use the header to redirect, always follow the exit to ensure that the script does not run, and end up with problems such as Headers Already Sent and so on.

...

However, don’t use your script that way, encrypt password with md5, sending all data to the session, not checking or setting token, or even without encrypting or encoding session values, directly matching the data the user sends.

Up to a md5 + salt would be better than this md5 alone, but that would also be a waste of time. It turns out that php has the function hash, which implements several secure encryption algorithms and easy to implement, you can start there, then you can go fixing several other things like CRFS, the very session and others. There are several questions here that may have answers the questions arise, just search.

0

A session, $_SESSION, is a way to store information (in variables) to be used on multiple pages. A session starts with the session_start() function. The session_start() function should be the first thing in your document. Before any HTML tags.

The command include_once("connected.php"); includes and evaluates the specified file during the execution of the script. In this case it causes your application to connect to a database. The connected.php file contains the access data of your Mysql database. The data is:

  • HOST: Host connection to the database.
  • USER: Access user to the connection database;
  • PASSWORD: Password to the database specified on the connection;
  • BASE: Name of the base you want to access.

The isset() function is used to check whether a variable has been defined (exist) or not, returning true (true) if defined and false (false) when not defined.

In addition, in your code valida.php page there are already several comments explaining in detail each step.

For those who are beginning to learn this is the basics and to finish it is good to follow the recommendations of the witches Bacco and Inkeliz. Even I’ll do it because I’m so outdated.

Browser other questions tagged

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