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!


Related Posts