Log In With Username / E-Mail in PHP Login System

PHP

Read {count} times since 2020

If your login system have both username and email parameter, then you can allow your users to log in with username or email. This is very easy for users, because if they forget their username, then they can log in with their email address. I will tell you an easy to way to set up log in with both username and email. It’s very easy.

A change in your SQL query can make this possible. Here’s how to do this.

Change Your Login Form

Since we’re going to make login with both username and email possible, we have to change the username field name to Username / E-Mail.

<label>Username / E-Mail</label>
<span style="line-height: 1.5em;"><input type="text" name="login" /></span>

We will use the name parameter as login because we accept both email and username.

If you are making a new login form, see this post on How to create a secure Login System. The users table in the post have username column containing the email of user. Here is a proper user table with username column containing username and email column containing the email of user :

CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` text NOT NULL,
`email` text NOT NULL,
`password` text NOT NULL,
`psalt` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

The others are all same except the login form. You should change the name to Username / E-Mail instead of just E-Mail.

SQL query Change

The login system should authorize if the user entered username or email. So we should change the SQL query like this :

SELECT id,password,psalt FROM users WHERE (username=:login OR email=:login) AND password=:pass

In PDO, we execute the above SQL query as :

$sql = $dbh->prepare("SELECT id,password,psalt FROM users WHERE (username=:login OR email=:login) AND password=:pass");
$sql->bindValue(":login", $_POST['login']);
$sql->bindValue(":pass", $_POST['pass']);
$sql->execute();

If you’re using this tutorial to create the login system, change the code :

$sql=$dbh->prepare("SELECT id,password,psalt FROM users WHERE username=?");
$sql->execute(array($email));
while($r=$sql->fetch()){
 $p=$r['password'];
 $p_salt=$r['psalt'];
 $id=$r['id'];
}

to this code :

$sql = $dbh->prepare("SELECT id,password,psalt FROM users WHERE username=:login OR email=:login");
$sql->bindValue(":login", $_POST['login']);
$sql->execute(array($email));
while($r=$sql->fetch()){
 $p=$r['password'];
 $p_salt=$r['psalt'];
 $id=$r['id'];
}

This will make MySQL to check columns that has the email or username value with what user entered.