Login does not work

Asked

Viewed 249 times

4

First time here, I got a code ready adapted to my college work, but the login does not check, accepts anything you put.

Creates login

<div id="nav">
    <div id="sup_direito">
        <div id="login">
            <input type="text" name="usuario" id="txUsuario" placeholder="login" required>
        </div>
        <div id="senha">
            <input type="password" name="senha" id="txSenha" placeholder="senha" required>
        </div>    
        <input type="submit" value="Entrar" />
    </div>
</div>

Validation 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
mysql_connect('localhost', 'root', 'usbw') OR trigger_error(mysql_error());
// Tenta se conectar a um banco de dados MySQL
mysql_select_db('sistemas para internet') OR trigger_error(mysql_error());

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

// Validação do usuário/senha digitados
$sql = "SELECT `cod_login`, `usuario` FROM `login` WHERE (`usuario` = '" . $usuario . "') AND (`senha` = '" . sha1($senha) . "') 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['cod_login'];
    $_SESSION['UsuarioNome'] = $resultado['usuario'];


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

Restricted code

<?php
// A sessão precisa ser iniciada em cada página diferente
if (!isset($_SESSION)){
    session_start();
}

// Verifica se não há a variável da sessão que identifica o usuário
if (!isset($_SESSION['UsuarioID'])) {
    // Destrói a sessão por segurança
    session_destroy();
    // Redireciona o visitante de volta pro login
    header("Location: index.php");
    exit;
}
?>
<h1>Página restrita</h1>
<p>Olá, <?php echo $_SESSION['UsuarioNome']; ?>!</p>
  • I think I better find a script with the functions mysqli() such as: http://www.eggslab.net/php-login-script/

  • See more here: http://answall.com/questions/579/por-que-n%C3%A3o-devo-usar-fun%C3%A7%C3%B5es-do-tipo-mysql

  • Here: http://answall.com/questions/47880/como-update-meu-c%C3%B3digo-mysql-para-mysqli

  • @Eduardoalmeida then you believe that the problem may be the way the code or logic was written?

  • @Gustavob. try to catch with 'mysqli', but referring to your question, try to change 'if (mysql_num_rows($query) != 1) {' by 'if (mysql_num_rows($query)<=0){', but then where you have 'echo "invalid login"', you change to how you have given serto think q will work

  • @Gustavob. man I think I found error kkkkkkkkkkkkkkkkkkk, missing boot the form on the login part changes the part of <div id="login"> by <form id="login" action="page that validates" type="POST"> but fails to change </div> by </form>

  • @Daniel Tranquil, I will review but I realized that I did not bring the note to the Service, I will have to test this your note later, thanks man for the tips

  • @Daniel didn’t work :(

  • @Eduardoalmeida Thanks for the tip, I managed to solve

Show 4 more comments

1 answer

1

Unfortunately my score does not allow comments but why is your database name with spaces instead of underline? Uses double quotes otherwise it does not detect the right database.

  • Sorry it took me so long to respond, I actually didn’t find a problem with my database, I followed Eduardo’s tip and it worked. And on the simple quotes, I took an example that was made available in class.

Browser other questions tagged

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