Explanation of login and profile validation code [closed]

2

I've been learning php though (I do not know if it's customary for a beginner) the code is getting a mess as I'm trying new things. I took some lessons on YouTube channel Celke however despite being well didactic some of the times it seems to me some unnecessary things when compared with other codes .. And in the code below I'm having trouble organizing myself, could anyone help me explain it?

The following code validates the 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 client.php

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

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


?>

I do not know if it's asking too much however someone could hack this code valid.php and help me with the client.php page so that I can enter db information in it, I want to dispose of the registrations carried out by the users in the however I 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.

    
asked by anonymous 02.04.2017 / 04:50

2 answers

2

There are reasons why you think there might be unnecessary things there, but it would also be correct to think that things are missing.

You could do 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 also: What is the best way to create a login system with php?

Instead of selecting all columns for the user, simply select the id and nivel of that user, and on the client page you check the id of that user and return the information from there. And whenever you use header to redirect, always follow it with exit to make sure that the script does not run, and it ends up with issues like Headers Already Sent and so on.

...

However, do not use your script in this way, encrypt password with md5 , sending all data to the session, not checking or setting token , or even without encrypting or encrypting session values, directly data that the user sends.

Up to 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 hash function, which implements several secure and easy-to-implement encryption algorithms, you can start there, then you can fix various other things like CRFS , session itself, and others. There are several questions here that may have answers to the doubts that arise, just search.

    
02.04.2017 / 13:29
0

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

The include_once statement ("connection.php"); includes and evaluates the specified file during script execution. In this case, your application connects to a database. The connection.php file contains the access data of your MySQL database. The data is:

  • HOST: Connection host to the database.
  • USER: Connection database access user;
  • PASSWORD: Password to access the database specified in 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 if set and false when not set.

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

  

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

    
02.04.2017 / 13:18