I am trying to create a login system. Below are the examples of my code.
index.php
<?php
session_start();
?>
<!doctype html>
<html lang="en">
<head>
<title>Login System</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="vendors/bootstrap/css/bootstrap.min.css">
<script src="vendors/jquery/jquery.min.js"></script>
<script src="vendors/bootstrap/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container-fluid">
<h2 class="text-center">Login System</h2>
<div class="card">
<div class="card-header">
<h4>Sign In</h4>
</div>
<div class="card-body">
<form role="form" action="loginform.php" method="post">
<div class="form-group">
<label for="inputusername">Username:</label>
<input class="form-control" type="text" id="inputusername" name="username" required>
</div>
<div class="form-group">
<label for="inputpassword">Password:</label>
<input class="form-control" type="text" id="inputpassword" name="password" required>
</div>
<?php
if (isset($_SESSION['error'])) {
echo '<div class="alert alert-danger text-center" role="alert">' . $_SESSION['error'] . '</div>';
}
?>
<button type="submit" class="btn btn-primary btn-block" name="login">Sign In</button>
</form>
</div>
</div>
</div>
</body>
</html>
<?php
unset($_SESSION['error']);
?>
loginform.php
<?php
session_start();
include 'dbconfig.php';
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = sha1($_POST['password']);
$login_query = "SELECT user_name, user_pass, user_role FROM users WHERE user_name = ?";
$login_stmt = mysqli_prepare($dbcon, $login_query);
mysqli_stmt_bind_param($login_stmt, "s", $username);
mysqli_stmt_execute($login_stmt);
mysqli_stmt_bind_result($login_stmt, $user_name, $user_pass, $user_role);
if (mysqli_stmt_fetch($login_stmt) == true) {
if ($user_pass == $password) {
session_regenerate_id();
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $user_name;
$_SESSION['userrole'] = $user_role;
header('Location: dashboard.php');
}
else {
$_SESSION['error'] = "You have entered incorrect password.";
header('Location: index.php');
}
}
else {
$_SESSION['error'] = "You have entered incorrect username.";
header('Location: index.php');
}
}
Is my code good enough to prevent SQL injection? If not, what can be done to improve?
P.S: As I have understood from resources found in the Internet that parameterized query is enough to prevent SQL injection. I might be wrong. If so, please explain.
Thanks.