Page that requires login does not even log in even with authenticated login

Asked

Viewed 31 times

-3

Hello, I’m studying PHP and I ended up getting stuck in a php system with login using sessions, I wanted the login page I created to take me to a user-only page, so I did it in an if that doesn’t allow people without login to enter it, but after creating it and testing I realized that even people who are logged in can not enter the users page, I imagine it is some kind of error with the sessions since the if includes a isset($_SESSION['id']) as a requirement to be able to see the page. Codes of the pages below:

Login validation:


include("../conexao.php");

$usuario = $_POST["usuario"];
$senha = md5($_POST["senha"]);

$busca = "SELECT * FROM usuario WHERE usuario = :usuario and senha = :senha";

$stmt = $conn->prepare($busca);
$stmt->bindParam(":usuario", $usuario);
$stmt->bindParam(":senha", $senha);
$stmt->execute();
$linha = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!$linha) {
    echo "esse usuario não existe";

}else{
    session_start();
    $_SESSION['id'] = $linha->id;
    $_SESSION['usuario'] = $linha->usuario;
    header("location:menu.php");
}

 ?>

User page:


session_start();
if (isset($_SESSION['id'])) {



 ?>
 <!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<h2>Pagina Usuario</h2>
<br><br>
<p>&nbsp;</p>
<a href="desconecta.php">desconectar</a>

<?php 

}else{

    header("location:desconecta.php");
} ?>
</body>
</html>

After stirring a little I got an error message, all I did was take the header(location:menu.php) from the validation page, and now I get 2 errors when trying to log in:

These errors refer to the last two lines of the validation page, the line $_SESSION['id'] = $linha->id; and the line $_SESSION['usuario'] = $linha->usuario;

  • $line is not an object, it is an array (because you used fetchAll)

  • Marcos, do as the bfavaretto said. Try trading for $stmt->fetch(PDO::FETCH_ASSOC) to see if it works.

  • I’m sorry but I’m still learning, would you be able to explain to me how this line of code would look so I can test? Would it just change $stmt->fetchAll(PDO::FETCH_ASSOC) to just fetch? Why if it was not working

1 answer

0

I managed to arrange doing a different approach, I followed what the bfavaretto said and changed $linha = $stmt->fetchAll(PDO::FETCH_ASSOC); for $linha = $stmt->fetch(PDO::FETCH_ASSOC);, I also changed the lines $_SESSION['id'] = $linha->id; and $_SESSION['usuario'] = $linha->usuario; for $_SESSION['id'] = $linha['id']; and $_SESSION['usuario'] = $linha['usuario']; respectively. I made changes to my user page so that I could use a if(isset($_GET['logout'])) on the logout page to destroy the session and there is no way someone can enter the users page without logging in before.

Browser other questions tagged

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