devgirl devgirl - 2 months ago 5
MySQL Question

Can't execute login function. No errors

I've been looking at my code for days, but can't seem to find the problem. I'm new in PHP, so I'm not really familiar with all of it.

Below is my code. No errors. No registered session variable values.

db-config.php

<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'mcsh';

$conn = mysqli_connect($host, $user, $pass, $db);

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>


login.php

<form id="user-login" action="index.php" method="POST">
<h1>Administrator Login</h1>
<input type="text" name="username" placeholder="Username" required/>
<input type="password" name="password" placeholder="Password" required/>
<button type="submit">Login</button>
<a href="/">Forgot your password?</a>
</form>

<?php
if (!empty($_POST)) {
if (!empty($_SESSION['username'])) {
header("Location: index.php");
}

$username = $_POST['username'];
$password = $_POST['password'];

include("../config/db-config.php");

$sql = "SELECT `userid`, `password` FROM users WHERE userid = '" . $username . "' AND userlevel = '99'";
$result = mysqli_query($conn, $sql);

if ($row = mysqli_fetch_assoc($result)) {
if (password_verify($password, $row['password'])) {
$_SESSION['username'] = $row['userid'];
header("Location: index.php");
exit;
}
else {
?>
<p class="msg" id="error">Invalid username or password. Please try again.</p>
<?php
}
}
else {
?>
<p class="msg" id="error">Invalid username or password. Please try again.</p>
<?php
}
}
?>


index.php

<?php
session_start();
include("../config/config.php");
if (empty($_SESSION['username'])) {
header("Location: login.php");
}
else {
//the rest of the index page...
?>

Answer

Your form in login.php submits to index.php. In index.php, if the username is not yet in the session, you are redirected back to login.php. There you check if (!empty($_POST)) { at the beginning of your PHP code.

$_POST will be empty, because you have redirected to that page, not POSTed to it, so the PHP code will not be executed.

Remove the action="index.php" and that form will submit to itself (login.php). Also, move the HTML form code below the PHP code so that you will not have output before the redirect header if the login is successful.