lundi 27 juin 2016

Having trouble getting PHP session to "remember" post data on refresh

I'm attempting to implement a simplistic user/login interface on my website.

I can 'login' just fine with a standard HTML form checking input against a database, but the username/password input is lost when I refresh the page after a successful login.

I did some research and discovered that session variables are a way to get around this. So I added a "session_start();" line at the top of each relevant page (login.php, index.php). Still, I am unable to refresh a page and stay "logged in".

Here's the code:

login.php -

<?php
session_start();
include "db_connect.php";
?>

<html>
<body>

<h3>Login form:</h3>

<form action='index.php' method='POST'>
  User:
  <input type="text" name="user">
  Pass:
  <input type="password" name="pass">
  <br><br>
  <input type="submit" value="Login">
</form>

</body>
</html>

index.php -

<?php
session_start();

$_SESSION['user'] = $_POST['user'];
$_SESSION["pass"] = $_POST['pass'];

$session_user = $_SESSION['user'];
$session_pass = $_SESSION['pass'];

?>

<html>
<head>
</head>

<body>
</body>

</html>


<?php
include "../db_connect.php";


$sql = "SELECT * FROM user WHERE (user = '$session_user' && password = '$session_pass')";
$result = $conn->query($sql);


if ($result->num_rows > 0) {

    // output data of each row
    while($row = $result->fetch_assoc()) {

        include "index_detail.php";
 }
} else {
    echo "There was an error logging in.";
}

?>  

My code logs in and displays what I want just once, but all form post data (user/pass) is lost upon refresh. What am I doing wrong? I really want to capture this "logged in" feel.

Thanks.

Aucun commentaire:

Enregistrer un commentaire