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
$email = sanitize_input($email);
$password = sanitize_input($password);
// Check if both fields are filled, if not, set appropriate error messages.
if (empty($email))
$emailErr = "Please enter your email";
if (empty($password))
$passwordErr = "Please enter your password";
// If either of the fields were empty,
// set old values for prefill and return.
if(!empty($emailErr) || !empty($passwordErr)) {
$emailOld = $email;
$passwordOld = $password;
return;
}
// Prepare and bind the sql statement
$stmt = $conn->prepare("SELECT user_id, username, email, password
FROM users WHERE email = :email;");
$stmt->bindParam(":email", $email);
// 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) {
$emailOld = $email;
$passwordOld = $password;
$emailErr = "This user either doesn't exist,
or has a different password.";
return;
}
// Load results to variables
$db_id = $result["user_id"];
$db_username = $result["username"];
$db_email = $result["email"];
$db_password = $result["password"];
// 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)){
$emailOld = $email;
$passwordOld = $password;
$emailErr = "This user either doesn't exist,
or has a different password.";
return;
}
$_SESSION["user_id"] = $db_id;
$_SESSION["user_name"] = $db_username;
$_SESSION["user_email"] = $db_email;
}
/**
* If user sent the form, process it.
* Either login user or set error message variables.
*/
if ($_SERVER["REQUEST_METHOD"] == "POST") {
attempt_login($_POST["email"], $_POST["password"]);
}
?>