PHP-code conflict - blank page

Asked

Viewed 103 times

0

The following code allows the user to log in and direct to a particular page, or log in as an administrator and direct to another page. The user login is working, however when logging out appears undefinied variable on line 28 and 29. And if I try to log in as an administrator and not redirect the page is empty.

<?php
require('config.php');

if (isset($_POST['email'])) {

    $stmt = $conn->prepare("SELECT password FROM registo WHERE email=?");
    $stmt->bind_param("s", $email);
    $email = $_POST['email'];
    $password = $_POST['password'];
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($pass);
    $stmt->fetch();
    if($stmt->num_rows > 0) {
        if(password_verify($password,$pass)) {
            $_SESSION['email'] = $email;
            $_SESSION['user'] = true;
            header("Location: home.php");
        } else {
            echo "<div class='form'>
                  <h3>Email/password is incorrect.</h3> <br>
                    Click here to <a href='memberarea.html'>Login</a>
                  </div>";
        }
    }
    } else {
        $ustmt = $conn->prepare("SELECT password FROM Admin WHERE email=?");
        $ustmt->bind_param("s", $email);
        $email = $_POST['email'];//linha 28
        $password = $_POST['password']; //linha 29
        $ustmt->execute();
        $ustmt->store_result();
        $ustmt->bind_result($pass);
        $ustmt->fetch();
        if($ustmt->num_rows > 0) echo "hello"; //linha 36 {
        if(password_verify($password,$pass)) {
                $_SESSION['email'] = $email;
                $_SESSION['Admin'] = true;
                header("Location: adminarea.html");
            } else { //linha 47
                echo "<div class='form'>
                        <h3>Email/password is incorrect.</h3> <br>
                        Click here to <a href='memberarea.html'>Login</a>
                      </div>";
            }

} else {
    echo "<div class='form'>
                        <h3>You are now logged out!.</h3> <br>
                        Click here to <a href='home.php'>Home</a>
                      </div>";
}
}
?>
  • you need to add the form code as well.

  • This code is very strange. You check if the variable email exists and executes one code if it does not execute another, but the two blocks need e-mail.

  • There is serious error of logic there. How you want to use $_POST['email'] if you are already saying that it does not exist when falling into the ELSE of condition if (isset($_POST['email'])).

  • what I want is if a user email is inserted to add to a certain page, if it is an administrator email to add to a different page. any suggested resolution?

  • I have been doing echo on each line. and on line 36 I put and complained of Else on line 47. pf edited the code! but I’m still not solving.

  • Yes, because it doesn’t make any sense to do what you did. The else cannot exist without the if.

  • (1) Are the e-mail and password of users and administrators informed in the same form? (2) How do you differentiate whether it is a user or admin login attempt? Will you first try logging in as a user and if you can’t, try as an admin? (3) Considering two different tables, is it possible that there are two equal user and admin registrations? (4) If yes, the account must be considered user or admin?

  • the form is the same, as I said before, before assigning bind Parameter was working perfectly. when logging in when I click submit detects whether it is user email or admin email, ie the code tries to see if it is user email if yes all right goes to x page. if it detects q is Admin email goes to another page! there are two different tables there is no chance that there are two equal entries.

  • Are you making this guarantee that there will not be equal records in code? By the way, first try to implement the Wendel solution. It makes a little more sense, by merging the two tables into one. Greatly simplifies the code.

Show 4 more comments

2 answers

0

The error of undefined variable occurs in item 18. The code is commented and is self-explanatory.

<?php

// (0) Não falta um session_start() aqui?

require('config.php');

// (1) Verifica-se se existe um e-mail na requisição:
if (isset($_POST['email'])) {

    // (2) Monta uma consulta à tabela registo (seria registro)?
    $stmt = $conn->prepare("SELECT password FROM registo WHERE email=?");

    // (3) Associa a variável $email à consulta:
    $stmt->bind_param("s", $email);

    // (4) Recupera os valores de $email e $password:
    $email = $_POST['email'];
    $password = $_POST['password'];

    // (5) Executa a consulta:
    $stmt->execute();

    // (6) Armazena os resultados
    $stmt->store_result();

    // (7) Associa a variável $pass ao resultado da consulta:
    $stmt->bind_result($pass);

    // (8) Obtém o resultado da consulta:
    $stmt->fetch();

    // (9) Verifica se há resultados:
    if($stmt->num_rows > 0) {

        // (10) Valida a senha informada comparando com a do banco de dados:
        if(password_verify($password,$pass)) {

            // (11) Armazena as sessões:
            $_SESSION['email'] = $email;
            $_SESSION['user'] = true;

            // (12) Redireciona o usuário:
            header("Location: home.php");

        // (13) A senha informada é inválida:
        } else {

            // (14) Exibe uma mensagem de erro:
            echo "<div class='form'>
                  <h3>Email/password is incorrect.</h3> <br>
                    Click here to <a href='memberarea.html'>Login</a>
                  </div>";
        }

    }

// (15) A variável $_POST["email"] não existe:
} else {

    // (16) Monta uma consulta à tabela Admin:
    $ustmt = $conn->prepare("SELECT password FROM Admin WHERE email=?");

    // (17) Associa a variável $email à consulta:
    $ustmt->bind_param("s", $email);

    // (18) Recupera os valores de $email, que não existe (vide 15), e $password:
    $email = $_POST['email']; //linha 28
    $password = $_POST['password']; //linha 29

    // (19) Executa a consulta:
    $ustmt->execute();

    // (20) Armazena os resultados da consulta:
    $ustmt->store_result();

    // (21) Associa a variável $pass ao resultado da consulta:
    $ustmt->bind_result($pass);

    // (22) Obtém o primeiro resultado:
    $ustmt->fetch();

    // (23) Veririca se há resultados:
    if($ustmt->num_rows > 0) {

        // (24) Verifica se a senha informada é válida:
        if(password_verify($password,$pass)) {

            // (25) Sim, armazena os valores em sessão:
            $_SESSION['email'] = $email;
            $_SESSION['Admin'] = true;

            // (26) Redireciona o usuário:
            header("Location: adminarea.html");

        // (27) A senha não é válida:
        } else {

            // (28) Exibe uma mensagem de erro:
            echo "<div class='form'>
                    <h3>Email/password is incorrect.</h3> <br>
                    Click here to <a href='memberarea.html'>Login</a>
                  </div>";
        }

    // (29) Não há registros:
    } else {

        // (30) Exibe uma mensagem de erro (logout? deveria ser dados incorretos):
        echo "<div class='form'>
                <h3>You are now logged out!.</h3> <br>
                Click here to <a href='home.php'>Home</a>
              </div>";
    }
}

?>

Solution will be given as soon as you define a plausible logic for the problem.

  • this code already gave in perfect ai I went to add the bind Parameter and it stopped working!

  • But it’s exactly your code, only commented on. It won’t work.

  • what I’m trying to say is that the code I put in the question before was working perfectly but then I put the bind Parameter and it stopped working!

  • If it was working, it was lucky. It shouldn’t. Read this commenting, answer it and we can see what is the best solution.

  • Answering your question, SESION_START is within config.php. if isset includes both user and admin if. this code recognizes whether the email belongs to a user or an admin and depending on the email entered makes different actions

0

To be able to do what you need you would have to create only one table to store all users. You have two registo and Admin. In this table you would have, for example:

user, email, password, type (Usuário e Administrador)

Assuming your table was named after usuarios, the code would look like this:

<?php
require('config.php');

// Verifica se está passando o e-mail e senha
if (isset($_POST['email']) and isset($_POST['password'])) {
    $email    = $_POST['email'];
    $password = $_POST['password'];

    // Seleciona o tipo pelo email e senha
    $stmt = $conn->prepare("SELECT type FROM usuarios WHERE email=? and password=?");
    $stmt->bind_param("ss", $email, $password);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($type);
    $stmt->fetch();

    if($stmt->num_rows > 0) {
        $_SESSION['email'] = $email;
        $_SESSION['type']  = $type; // crio uma sessão com o tipo para facilitar a identificação ao invéz de ter duas sessões (user e admin)

        if $type = 'usuario' { // Se for usuário
            header("Location: home.php");
        } else { // Senão é admin
            header("Location: adminarea.html");
        }
    } else { // Caso não tenha encontrado pelo e-mail e senha informado
        echo "<div class='form'>
            <h3>Email/password is incorrect.</h3> <br>
            Click here to <a href='memberarea.html'>Login</a>
            </div>";
    }
}
?>

Browser other questions tagged

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