To allow users to login with either their username or email, you need to modify your login system to check both fields during the authentication process. Here are the general steps to implement this functionality:

  1. Modify the login form: Modify the login form to allow users to enter either their username or email. You can use a single input field and allow the user to enter either their username or email, or you can use two separate fields and check both fields during the authentication process.

  2. Modify the authentication process: Modify the authentication process to check both the username and email fields. You can do this by first checking if the input is an email address or a username, and then querying the database for a match on either the username or email field. If a match is found, you can verify the password and log the user in.

Here's an example of how to modify the authentication process in PHP:

php
$username_or_email = $_POST['username_or_email']; $password = $_POST['password']; // Check if the input is an email address or a username if (filter_var($username_or_email, FILTER_VALIDATE_EMAIL)) { // The input is an email address, so query the database for a match on the email field $query = "SELECT * FROM users WHERE email = '$username_or_email'"; } else { // The input is a username, so query the database for a match on the username field $query = "SELECT * FROM users WHERE username = '$username_or_email'"; } $result = mysqli_query($conn, $query); if ($result && mysqli_num_rows($result) > 0) { // A match was found, so verify the password $row = mysqli_fetch_assoc($result); if (password_verify($password, $row['password'])) { // Password is correct, so log the user in $_SESSION['user_id'] = $row['id']; header("Location: home.php"); exit; } else { // Password is incorrect, so display an error message $error = "Invalid password"; } } else { // No match was found, so display an error message $error = "Invalid username or email"; }

In this example, we're checking if the input is an email address or a username using the FILTER_VALIDATE_EMAIL filter. We're then constructing a SQL query to check for a match on either the email or username field, and querying the database using mysqli_query(). If a match is found, we're verifying the password using password_verify() and logging the user in if the password is correct. If no match is found or the password is incorrect, we're displaying an error message to the user.

Have questions or queries?
Get in Touch