- Passwords are stored in plain text just for the sake of ease, this will never be a deployed website. I know I should use Password_hash and that plain text passwords are a huge security vulnerability.
The issue I'm facing is that when a username and password is typed in, even if the values are not present in the database, the Submit.php line elseif ($query) executes and redirects the user back to the mainpage. The functionality I was expecting is that should incorrect credentials be entered into the form, such as the correct username but wrong password or vice versa it would be caught by if(!$query) and the error message inserted into the HTML form at the line . Since PDOStatement::fetch should return false, when there is a failure to return a row. So my understand was that if username and password, or one of the two do not match no rows should be available and a false would be the result. My assumption is that the fetch() sees to be evaluating to true always, or I have made an error in my boolean login in my if statements.
Login.php:
<form class="Form" method = "post" name="form" action = "Login.php">
<h1> Login </h1>
<hr>
<div class="Entry">
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name ="username" id = "username" required> <br>
<label for="password"><b>Password</b></label>
<input type ="password" placeholder="Enter a Password" name = "password" id="password" required> <br> <br>
<button type="submit" value ="login" name="submit" class="registerbtn"><b>Login</b></button>
<br><br>
<?= $errmsg ?>
<a href="Register.php"> Register if you don't have an account already</a>
</div>
</div>
</form>
Submit.PHP:
<?php
session_start();
$errmsg = '';
$errors = array();
//This connects to the localhost database.
$dsn = "mysql:host=localhost;dbname=labwebsite";
$user = "root";
$passwd = "";
try
{
$pdo = new PDO($dsn, $user,$passwd);
}
catch(PDOEXception $e)
{
$strerr = $e->getMessage();
$format = 'Failed to connect to Database: %s';
echo sprintf($format, $strerr);
exit;
}
if (isset ($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$query = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1");
$query->bindParam(1, $username, PDO::PARAM_STR, 12);
$query->bindParam(2, $password, PDO::PARAM_STR, 12);
$query->execute();
$query->fetch();
if(!$query)
{
array_push($errors,"Username and password is required");
$errmsg = '<span id = "error" class = "errbox">'.implode('<br/>', $errors).'</span>';
exit();
}
elseif ($query)
{
$_SESSION ['username'] = $username;
$_SESSION ['permission'] = $permission;
$_SESSION ['success'] = "You are now logged in";
echo "success!"; //test to see if this was being executed.
header ("location: index.php");
exit();
}
$query->close();
}
$pdo=null;
?>