五分钟明白PHP 聚合版登录模式 (选择帐号,邮箱,或者帐号密码登入)
五分钟明白PHP 聚合版登录模式 (同一表单手机号,邮箱,或者帐号密码登入)
在平时的登入功能中,我们有时候会遇见一个登录中,可以选择要邮箱、手机电话、或者帐号登入,今天无聊,就突然想到了这种模式,就尝试了一下,发现还是挺简单的。没有封装成类,部分就封装了函数,封装类也很贱大。
下面用代码来讲述我们的功能,手机也可以登入,邮箱也可以登入的模式
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="test.php" method="post">
<p><input type="text" name="uname" placeholder="帐号、邮箱或帐号"></p>
<p><input type="password" name="passwd" placeholder="密码"></p>
<p><input type="submit" value="登入"></p>
</form>
</body>
</html>
php代码
<?php
list($uname, $passwd) = array($_POST['uname'], $_POST['passwd']);
$UserType = checkUserType($uname);
$result = query($UserType, $uname,$passwd);
if ($result == 'OK') {
echo '登入成功';
}
/**
* 查询是否登入成功,
* @param $UserType
* @param $uname
*/
function query($UserType, $uname,$passwd)
{
try {
$where = getUserLoginType($UserType, $uname);
$dsn = 'mysql:host=127.0.0.1;dbname=test';
$pdo = new PDO($dsn, 'root', '');
$query = 'SELECT * FROM `user` WHERE ' . $where;
$result = $pdo->query($query)->fetch();
if (!$result) {
switch ($UserType) {
case 1:
throw new \Exception('不存在邮箱');
break;
case 2:
throw new \Exception('不存在此手机用户');
break;
case 3:
throw new \Exception('帐号不存在');
break;
default:
throw new \Exception('数据类型错误');
break;
}
}
if($result['passwd']!=$passwd){
throw new \Exception('密码错误');
}
return 'OK';
} catch (\Exception $exception) {
echo $exception->getMessage();
}
}
/**
* 获取用户登录帐号类型
* @param $UserType
* @param $uname
* @return string
* @throws Error
*
*/
function getUserLoginType($UserType, $uname)
{
switch ($UserType) {
case 1:
$where = 'email = \'' . $uname . '\'';
break;
case 2:
$where = 'phone = \'' . $uname . '\'';
break;
case 3:
$where = 'uname = \'' . $uname . '\'';
break;
default:
throw new \Exception('数据类型错误');
break;
}
return $where;
}
/**
*判断登录帐号类型
* @param $username
* @return int
*/
function checkUserType($username)
{
if (filter_var($username, FILTER_VALIDATE_EMAIL)) {
//是邮箱返回type 1
return 1;
} else if (preg_match("/^1[34578]{1}\\d{9}$/", $username)) {
//是手机返回type 2
return 2;
}
//是帐号返回type 3
return 3;
}
数据库
| id | phone | uname | passwd |
|---|

浙公网安备 33010602011771号