php 在php中使用用户名或电子邮件地址登录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10419137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
login with username or email address in php
提问by SureshKumar Vegesna
I am trying to create a login with username or email
我正在尝试使用用户名或电子邮件创建登录名
My code is:
我的代码是:
$username=$_REQUEST['login'];
$email=$_REQUEST['login'];
$password=$_REQUEST['password'];
if($username && $password) {
$query="select * from user_db where username='$username' and password='$password'";
} else if ($email && $password) {
$query="select * from user_db where email='$email' and password='$password'";
}
Login with username is success but login with email is not working. Please help me!
使用用户名登录成功,但使用电子邮件登录无效。请帮我!
回答by Recognizer
The login parameter is the same for both email and username. Not exactly incorrect if you have a single login box that accepts either.
电子邮件和用户名的登录参数相同。如果您有一个接受任一登录框的登录框,那么这并不完全不正确。
You could put the condition in the query itself if you're not sure if it's an email or username.
如果您不确定它是电子邮件还是用户名,您可以将条件放在查询本身中。
$login=$_REQUEST['login'];
$query = "select * from user_db where ( username='$login' OR email = '$login') and password='$password'"
Edit:A PDO-like solution is much more preferred nowadays as the above is subject to SQL injection. The logic stays the same, but you'd have it look something like this:
编辑:现在更喜欢类似 PDO 的解决方案,因为上述内容受到 SQL 注入的影响。逻辑保持不变,但你会看到它看起来像这样:
$query = "
SET @username = :username
SELECT * FROM user_db
WHERE ( username = @username OR email = @username)
AND password = :password
";
$statement = $pdoObject->prepare($query);
$statement->bindValue(":username", $login, PDO::PARAM_STR);
$statement->bindValue(":password", $password, PDO::PARAM_STR);
$statement->execute();
回答by gcochard
You are setting the same value to two variables, and then using an if/else. Both if statements are equivalent.
您正在为两个变量设置相同的值,然后使用 if/else。两个 if 语句是等价的。
You need to figure out if $_REQUEST[login]contains a valid email address, and if so use the email field of the database. Otherwise, use the username field.
您需要确定是否$_REQUEST[login]包含有效的电子邮件地址,如果是,则使用数据库的电子邮件字段。否则,请使用用户名字段。
Also, you should not be putting variables directly into the query. Use prepared statements.
此外,您不应将变量直接放入查询中。使用准备好的语句。
回答by DarthVader
$username=$_REQUEST['login'];
$email=$_REQUEST['login'];
This is wrong, you are using $_REQUEST['login']for both email and username. Why don't you just use email?
这是错误的,您同时使用$_REQUEST['login']电子邮件和用户名。你为什么不直接使用电子邮件?
If $_REQUEST['login']doesn't have email address, of course this wont return you anything.
如果$_REQUEST['login']没有电子邮件地址,当然这不会返回任何东西。
Also, both of your if statements will always execute, unless the fields are empty. right?
此外,除非字段为空,否则您的两个 if 语句都将始终执行。对?
Take the login out, enforce the users to login with email addresses. also, take md5 of the password. who stores raw passwords these days?
取消登录,强制用户使用电子邮件地址登录。另外,取密码的md5。这些天谁存储原始密码?
回答by user2746803
if (validate_username($username)) {
$query="select * from user_db where username='".$username".' and password='".validate_password($password)."'";
} else if (validate_email($email)) {
$query="select * from user_db where email='".$email."' and password='".validate_password($password)."'";
}
回答by excoret
Well i know this is an old post but i've found that some people are still going to view it so i wanted to put a easy way to allow both email and username on the same input
好吧,我知道这是一篇旧帖子,但我发现有些人仍然会查看它,所以我想提供一种简单的方法来允许在同一输入中同时输入电子邮件和用户名
my code is as follows
我的代码如下
if
(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $name_of_same_input) )
{
$un_check = mysql_query("SELECT uname FROM eusers WHERE uname = '' ") or die(mysql_error());
echo "loging in with username"; //code
}
elseif
(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $name_of_same_input) )
{
$un_check = mysql_query("SELECT umail FROM eusers WHERE umail = '' ") or die(mysql_error());
echo "loging in with email"; //code
}
回答by Ashish Bharam
<?php
require "connectdb.php";
$email =$_POST["email"];
$mobile = $_POST["mobile"];
$password =$_POST["password"];
//Test variables
//$email = "[email protected]";
//$mobile = "9876543210";
//$password ="@!b7885a$";
$sql_query = "SELECT email FROM RegisterUser WHERE `email` LIKE '$email' OR `mobile` LIKE '$mobile' AND `password` LIKE '$password';";
$result = mysqli_query($con,$sql_query);
if(mysqli_num_rows($result) > 0 )
{
$row = mysqli_fetch_assoc($result);
$email = $row["email"];
echo "Login Successful...Welcome ".$email;
}
else
{
echo "Login Failed...Incorrect Email or Password...!";
}
?>
回答by Damian Nass
Hi, for me works something like this:
if ( !isset($_POST['emailuser'], $_POST['userPass']) ) { // Could not get the data that should have been sent. die ('Please fill both the username and password field!'); } $emailuser = ($_POST['emailuser']); $emailuser = trim($emailuser); if ($stmt = $con->prepare('SELECT userEmail or userName, userPass FROM users WHERE userEmail = ? or userName = ?')) { // Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s" $stmt->bind_param('ss', $emailuser, $emailuser); $stmt->execute(); // Store the result so we can check if the account exists in the database. $stmt->store_result(); if ($stmt->num_rows > 0) { $stmt->bind_result($userName, $userPass); $stmt->fetch(); // Account exists, now we verify the password. // Note: remember to use password_hash in your registration file to store the hashed passwords. if (password_verify($_POST['userPass'], $userPass)) { // Verification success! User has loggedin! // Create sessions so we know the user is logged in, they basically act like cookies but remember the data on the server. session_regenerate_id(); $_SESSION['loggedin'] = true; $_SESSION['name'] = $emailuser; $_SESSION['emailuser'] = $userName; header('location: /menu.php'); } else { echo 'Incorrect password!'; } } else { echo 'Incorrect username!'; } $stmt->close(); } ?>
嗨,对我来说是这样的:
if ( !isset($_POST['emailuser'], $_POST['userPass']) ) { // Could not get the data that should have been sent. die ('Please fill both the username and password field!'); } $emailuser = ($_POST['emailuser']); $emailuser = trim($emailuser); if ($stmt = $con->prepare('SELECT userEmail or userName, userPass FROM users WHERE userEmail = ? or userName = ?')) { // Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s" $stmt->bind_param('ss', $emailuser, $emailuser); $stmt->execute(); // Store the result so we can check if the account exists in the database. $stmt->store_result(); if ($stmt->num_rows > 0) { $stmt->bind_result($userName, $userPass); $stmt->fetch(); // Account exists, now we verify the password. // Note: remember to use password_hash in your registration file to store the hashed passwords. if (password_verify($_POST['userPass'], $userPass)) { // Verification success! User has loggedin! // Create sessions so we know the user is logged in, they basically act like cookies but remember the data on the server. session_regenerate_id(); $_SESSION['loggedin'] = true; $_SESSION['name'] = $emailuser; $_SESSION['emailuser'] = $userName; header('location: /menu.php'); } else { echo 'Incorrect password!'; } } else { echo 'Incorrect username!'; } $stmt->close(); } ?>
回答by Nathaniel Ford
$username=$_REQUEST['username'];//I'm assuming your code here was wrong
$email=$_REQUEST['email'];//and that you have three different fields in your form
$password=$_REQUEST['password'];
if (validate_username($username)) {
$query="select * from user_db where username='".$username".' and password='".validate_password($password)."'";
} else if (validate_email($email)) {
$query="select * from user_db where email='".$email."' and password='".validate_password($password)."'";
}
//... elsewhere...
function validate_username(&$username) {
if (strlen($username) <= 1) { return false; }
//return false for other situations
//Does the username have invalid characters?
//Is the username a sql injection attack?
//otherwise...
return true;
}
function validate_email(&$email) {
//same deal as with username
}
function validate_password(&$password) {
//same deal as with username
}
Note, if you have only two fields (login and password), then the distinction between email and username is meaningless. Further note that you should really be using PHP PDOto construct and execute your queries, to prevent security breaches and make your life waaay easier.
请注意,如果您只有两个字段(登录名和密码),那么电子邮件和用户名之间的区别是没有意义的。进一步注意,您应该真正使用PHP PDO来构建和执行您的查询,以防止安全漏洞并使您的生活更轻松。

