How to Login with Username or Email Id using PHP & MYSQL

Last modified on by Karthikeyan K

In many social networking sites, they allow users to login with Username or Email using PHP. I would say this is the fantastic feature for whose all who forgot their usernames.

I strongly believe that most of the people will forgot their Usernames rather than Email id.

Here I am going to explain you about how to allow users to login with username or email Id using PHP & MYSQL.

How to Login using Username or Email Id with PHP & MYSQL

In this project, I have used PHP’s native function called filter_var(). The filter_var() function filters a variable with the specified filter. Returns the filtered data on success or FALSE on failure

I wrote a small function that will find whether the user entered is email or username

function Is_email($user)
//If the username input string is an e-mail, return true
if(filter_var($user, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;

The above function will returns true If user has given Email Id or it returns false. Based on this we will easily switch the query

Database Structure


Complete Code

if($_POST['username'] != '' && $_POST['password'] != '')
$name = $_POST['username'];
$pass = md5($_POST['password']);

$check_email = Is_email($name);
// email & password combination
$query = mysql_query("SELECT * FROM `users` WHERE `email` = '$name' AND `password` = '$pass'");
} else {
// username & password combination
$query = mysql_query("SELECT * FROM `users` WHERE `username` = '$name' AND `password` = '$pass'");
$rows = mysql_num_rows($query);
if($rows > 0)
//successfull login
$_SESSION['username'] = $name;
} else {
$msg = "Invalid Login Credentials";

} else {
$msg = "Please Provide All Details";

Please don’t forget to share and subscribe to latest updates of the blog. Comments and feedbacks are always welcome!


You May Also Like

4 Responses

  1. Dave says:

    Why so complicated? You don’t need to create a function to determine if the user is logging in with an email address or a username. Just let MySQL handle it – here is an example:

    $name = $_POST[‘username’]; # userid can be an email address or a username
    $pass = md5($_POST[‘password’]); # Password

    $query = mysql_query(“SELECT * FROM `users` WHERE ‘$name’ IN (username, email) AND `password` = ‘$pass'”);

    Also, your example is vulnerable to SQL injection… At that point, you should start using MySQLi or PDO + prepared statements. Don’t use this example in a production environment…

  2. Sumit says:

    Script is not working kindly provide the database

  3. Sagar SN says:

    Thanks Karthikeyan and Dave that helped me a lot, i followed the same code for login using email/phone

Leave a Reply

Your email address will not be published. Required fields are marked *