I am learning PHP. I am working on a simple login system with procedural PHP. I am getting username/password from this form:
Form Code:
<form action="includes/login.php" method="POST">
<div class="form-group">
<input name="username" type="text" placeholder="What is your username?" class="form-control">
</div>
<div class="input-group">
<input name="user_password" type="password" placeholder="Your password goes here" class="form-control" >
<span class="input-group-btn">
<button name="login" class="btn btn-primary" type="submit"> Login
</button>
</span>
</div>
</span>
</form>
And sending it to login.php
where I check that information with the database. Bear with me, I'm learning, so what I am trying to do is to redirect users to index.php
if $username
and $password
doesn't match with $db_username
and $db_user_password
After some researching on StackOverFlow I found that I need to use <?php ob_start(); ?>
at the top of the file but it still won't work. It throws the following error when I log in with the wrong user and password.
I tested with multiple browsers, restarted apache/MySQL many times, saved all files multiple times.
Here's my code in login.php file:
<?php ob_start(); ?>
<?php include "db.php"; ?>
<?php
if (isset($_POST['login'])) {
$username = $_POST['username'];
$user_password = $_POST['user_password'];
$username = mysqli_real_escape_string($connection, $username);
$user_password = mysqli_real_escape_string($connection, $user_password);
$query = "SELECT * FROM users WHERE username = '{$username}' ";
$fetch_username_query = mysqli_query($connection, $query);
if (!$fetch_username_query) {
die("Fetch Username Query Failed" . mysqli_error($connection));
}
while ($row = mysqli_fetch_array($fetch_username_query)) {
$db_username = $row['username'];
$db_user_id = $row['user_id'];
$db_user_password = $row['user_password'];
$db_user_firstname = $row['user_firstname'];
$db_user_lastname = $row['user_lastname'];
$db_user_role = $row['user_role'];
}
if ($username !== $db_username || $user_password !== $db_user_password) {
header("Location ../index.php");
}
}
?>
My db.php file has this:
<?php
$db['db_host'] = "localhost";
$db['db_user'] = "root";
$db['db_pass'] = "";
$db['db_name'] = "cms";
foreach ($db as $key => $value) {
define(strtoupper($key), $value);
}
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
die("MySQL connection failed");
}
?>
Also here's a screenshot from my phpMyAdmin users table:
I am using XAMPP on Windows 10 (PHP 7.4)
PS: I'm learning Procedural PHP first (basics), I am not using prepared_statement as of now, I'm aware of it, will learn that later. My problem is with undefined variable
. Thanks, team :)