I'm hoping someone would be able to identify if my code is prone to SQL injections, and just overall see if there is anything that could be done better.
This is also my first time using MySQLi prepared statements in a login script.
<?php
include('../include/sessions.php');
if(isset($_POST['username']))
{
$username = mysqli_real_escape_string($dbc, $_POST['username']);
$password = mysqli_real_escape_string($dbc, $_POST['password']);
$select = "SELECT username, firstname, lastname, email,
userlevel, `password` FROM users WHERE username = ?;";
$stmt = mysqli_stmt_init($dbc);
if(!mysqli_stmt_prepare($stmt, $select))
{
echo "Error: " . mysqli_stmt_error($stmt);
}
else
{
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
$dbusername = htmlentities(stripslashes($row['username']));
$dbfirstname = htmlentities(stripslashes($row['firstname']));
$dblastname = htmlentities(stripslashes($row['lastname']));
$dbemail = htmlentities(stripslashes($row['email']));
$dbuserlevel = htmlentities(stripslashes($row['userlevel']));
$dbpassword = htmlentities(stripslashes($row['password']));
if(password_verify($password, $dbpassword)) // used bcrypt to hash password
{
// not sure if this is the best way to set the sessions
$_SESSION['username'] = $dbusername;
$_SESSION['firstname'] = $dbfirstname;
$_SESSION['lastname'] = $dblastname;
$_SESSION['email'] = $dbemail;
$_SESSION['userlevel'] = $dbuserlevel;
header("Location: ../cust/home.php");
}
else
{
echo "The username/password combination does not match our records. Please try again.";
}
}
}
?>
My sessions.php looks like this:
<?php
if(!isset($_SESSION)){session_start();}
include("database.php");
$username = $_SESSION['username'];
$firstname = $_SESSION['firstname'];
$lastname = $_SESSION['lastname'];
$email = $_SESSION['email'];
$userlevel = $_SESSION['userlevel'];
// I started using the below if statement in conjunction with a .htaccess file to prevent
// anyone from attempting navigate the directories through the URL.
// I am sure there is another way to do this.
if($username == "" || $_SESSION['username'] == "" || $userlevel != '9')
{
header('Location: ../index.php');
}
?>
Using this code, I am successfully able to login and set the session variables.