Failed DB connection, cannot proceed!
If you see this error in production,
please shoot me an email with helpful details.
");
include_once($GLOBALS['COMMONS']."/footer.php");
die();
}
// Sanitize inputs
$username = sanitize_input($username);
$password = sanitize_input($password);
// Check if both fields are filled, if not, set appropriate error messages.
if (empty($username))
$usernameErr = "Please enter your username.";
if (empty($password))
$passwordErr = "Please enter your password.";
// If either of the fields were empty,
// set old values for prefill and return.
if(!empty($usernameErr) || !empty($passwordErr)) {
$usernameOld = $username;
$passwordOld = $password;
return;
}
// Prepare and bind the sql statement
$stmt = $conn->prepare("SELECT user_id, password,
created_at, permissions FROM users WHERE username = :username;");
$stmt->bindParam(":username", $username);
// Execute the statement
$stmt->execute();
// Fetch the values
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// If the user isn't in the database, set errors, old values, and return.
if(!$result) {
$usernameOld = $username;
$passwordOld = $password;
$usernameErr = "This user either doesn't exist,
or has a different password.";
return;
}
// Load results to variables
$db_id = $result["user_id"];
$db_password = $result["password"];
$db_permissions = $result["permissions"];
// If user entered incorrect password, set errors, old values, and return.
// Keep the error string the same as non-existing so that an attacker
// cannot asses whether a given user has an account.
if(!password_verify($password, $db_password)){
$usernameOld = $username;
$passwordOld = $password;
$usernameErr = "This user either doesn't exist,
or has a different password.";
return;
}
// Set the session logged in user.
$_SESSION["current_user"] = new User($db_id, $username, $db_permissions);
}
/**
* If user sent the form, process it. This starts a session.
* Either login user and redirect to index or set error message variables.
*/
if (isset($_POST["submit"])) {
session_start();
// Log user out
$_SESSION["current_user"] = null;
// Attempt to log in
attempt_login($conn, $_POST["username"], $_POST["password"]);
// If login succeeded, go to index
if($_SESSION["current_user"] != null) {
header("Location: "."http://www.zdenekborovec-dev.cz");
}
}
?>