Login and password with permission level in php

Asked

Viewed 2,313 times

-1

I am set up a system to facilitate communication and support to representatives of the company where I work. The rest of the page already exists, but I need to make each type of user be directed to a different page.

One of the biggest problems I’m facing is that there’s always the message that the mysql_connect no longer works and which should be replaced by the mode PDO.

Someone there can help me?

Follows the code

<?php

// Verifica se houve POST e se o usuário ou a senha é(são) vazio(s)
if (!empty($_POST) AND (empty($_POST['usuario']) OR empty($_POST['senha']))) {
    header("Location: index.php"); exit;
}

// Tenta se conectar ao servidor MySQL
mysqli_connect('localhost', 'root', '') or trigger_error(mysql_error());
// Tenta se conectar a um banco de dados MySQL
mysqli_select_db('novosistema') or trigger_error(mysql_error());

$usuario = mysqli_real_escape_string($_POST['usuario']);
$senha = mysqli_real_escape_string($_POST['senha']);

// Validação do usuário/senha digitados
$sql = "SELECT `id`, `nome`, `nivel` FROM `usuarios` WHERE (`usuario` = '". $usuario ."') AND (`senha` = '". sha1($senha) ."') AND (`ativo` = 1) LIMIT 1";
$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 {
    // Salva os dados encontados na variável $resultado
    $resultado = mysql_fetch_assoc($query);

    // Se a sessão não existir, inicia uma
    if (!isset($_SESSION)) session_start();

    // Salva os dados encontrados na sessão
    $_SESSION['UsuarioID'] = $resultado['id'];
    $_SESSION['UsuarioNome'] = $resultado['nome'];
    $_SESSION['UsuarioNivel'] = $resultado['nivel'];

    // Redireciona o visitante
    header("Location: restrito.php"); exit;
}

?>
  • http://answall.com/questions/579/por-que-n%C3%A3o-should-use-fun%C3%A7%C3%B5es-do-tipo-mysql

  • If you are using any version of PHP 5.5+ should keep in mind that the library mysql_* was discontinued, one should look for alternatives as cited in the link passed above, as the mysqli_*, PDO, or libraries of other frameworks

2 answers

0

mysql_connect no longer works and should be replaced by PDO mode.

We should not use this function anymore, for the simple fact of the PHP have more sophisticated and more secure methods. in addition to mysql have limitations you can use the mysqli that it is an improved method. no stackoverflow we have topics addressing this issue:Why we should not use mysql type functions.

This same link explains the benefits of using the PDO class.

Now let’s talk a little bit about logic. you need to redirect the user to a specific page according to your access level. you can simply do a check

se  sessãonivel == administrador então acesse pagina x
se  sessãonivel == cliente entao acesse pagina y.

create a function to verify that the x user is accessing the y page and redirect to the correct page.

0

Cara I suggest you update the access with the library PDO, which is much easier and safer. In case you are used to programming PHP OO, use classes to receive the values of $_SESSION.

Here’s an example I used for login validation with PDO

<?php
// Conexão Com o banco de dados
// INCLUI A CLASSE PARA CONEXÃO COM BANCO DE DADOS
    function __autoload($classe){
        if(file_exists("pdo/{$classe}.class.php")){
            require_once "pdo/{$classe}.class.php";
        }
    }

// Inicia sessões
session_start();

// Recupera o login
$login = isset($_POST["login"]) ? (trim($_POST["login"])) : FALSE;
// Recupera a senha, a criptografando em MD5
$senha = isset($_POST["senha"]) ? md5(trim($_POST["senha"])) : FALSE;

// Usuário não forneceu a senha ou o login
    if(!$login || !$senha){  
        header("Location: erro_login.php");
    exit;
    }

$Consulta_Login     =   "SELECT id, nome, sobre_nome, data_nascimento, senha, resgata_senha, email, estado, cidade, iurd
                            FROM login_usuario
                        WHERE email = '" . $login . "'";

        $PDO    =   ConexaoBanco::open();
        $result =   $PDO->query($Consulta_Login);

        if($result->rowCount()){
            $linhas = $result->fetch(PDO::FETCH_OBJ);

            if(!strcmp($senha, $linhas->senha)){
                $_SESSION["id_login_usuario"]   =   $linhas->id;
                $_SESSION["confirma_cadastro"]  =   "0";

                    switch ($linhas->nome) {    

                        default;
                            //header("Location: loading.html");
                            header("Location: loading.php");
                        break;

                    }
                    exit;
            }else{
                // Senha inválida
                    header("Location: erro_login.php");
                exit;
            }

        }else{
            //Login Invalido
                header("Location: erro_login.php");
            exit;
        }   

        $PDO    =   null;


?>

Regarding the access level, there are several ways, since you entered a level field in the bank, such as a Switch to have actions according to levels.

Browser other questions tagged

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