Since you have all your code for login, processing and showing the user is logged in at the same page with no redirect after the user is successful logged in, it takes you 2 submits to see the logged in page.
I would suggest you splitting your login page from what you currently have into a login.php
and a home.php
.
Also you should avoid querying for username
and password
, you should only need to retrieve the username
and compare the password
instead and also avoid saving the password on the session its extremely unneeded.
login.php
would have:
<?php
session_start();
$db_host = '';
$db_user = '';
$db_pass = '';
$db_name = '';
if (isset($_SESSION['username']))
{
header("Location: home.php");
}
else
{
if (isset($_POST['submit']))
{
if (isset($_POST['username']) && isset($_POST['password']))
{
$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if ($con->connect_error)
{
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
$sql = "SELECT username, password FROM login WHERE username = ?";
if (!$result = $con->prepare($sql))
{
die('Query failed: (' . $con->errno . ') ' . $con->error);
}
if (!$result->bind_param('s', $_POST['username']))
{
die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
}
if (!$result->execute())
{
die('Execute failed: (' . $result->errno . ') ' . $result->error);
}
$result->store_result();
if ($result->num_rows == 0)
{
die('No username found...');
}
$password = hash('sha256', $_POST['password']);
$result->bind_result($db_username, $db_password);
$result->fetch();
if ($password == $db_password)
{
$_SESSION['username'] = $db_username;
header("Location: home.php");
exit;
}
else
{
$error = "Username or password does not match...";
}
}
else
{
$error = "Fill the username and password to login...";
}
}
}
?>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<?php if (isset($error)) echo $error, '<br>'; ?>
<form method="POST" action="index.php">
<label>Username</label><br /><input type="text" name="username" value=""><br />
<label>Password</label><br /><input type="password" name="password" value=""><br />
<input type="submit" name="submit" value="Login">
</form>
</body>
</html>
And at home.php
:
<?php
session_start();
if (!isset($_SESSION['username']))
{
header("Location: login.php");
exit;
}
?>
<p><? echo $_SESSION["username"]; ?> is currently logged in.
<form action="logout.php">
<input type="submit" value="Log out">
</form>