用户管理器/登录/注册/退出 [整合版]
带类型的请求:
如:serHandle.php?action=login
<?php
// 用户管理器/登录/注册/退出
// 1.开启会话
session_start();
// 2. 加载用户数据
require __DIR__ . '/../config/common.php';
$users = require DATA_PATH . '/users.php';
// 3. 获取get请求参数
$action = strtolower($_GET['action']);
// 4. 操作白名单
$allowOpts = ['login','register', 'logout'];
// 5. 操作结果默认值
$prompt = false;
// 6. 检测操作类型是否合法?
if (!in_array($action, $allowOpts)) {
echo <<< TIPS
<script>
alert('操作类型非法');
location.href='../login.php';
</script>
TIPS;
die;
}
// 7. 判断要做什么
switch ($action) {
// 7.1 登录
case 'login':
// 获取json,转array
$json = file_get_contents('php://input');
$user = json_decode($json, true);
$email = $user['email'];
$password = md5($user['password']);
$result = array_filter($users, function ($user) use ($email, $password) {
return $user['email'] === $email && $user['password'] === $password;
});
if (count($result) === 1) {
$prompt = true;
// 登录成功,将用户信息写入session
$_SESSION['user'] = array_pop($result);
}
break;
// 7.2. 注册
case 'register':
$oriCount = count($users);
$json = file_get_contents('php://input');
$user = json_decode($json, true);
$user['password'] = md5($user['password']);
$user['id'] = count($users)+1;
$users[] = $user;
if (count($users) === $oriCount + 1) {
$prompt = true;
}
break;
// 7.3 退出
case 'logout':
if (session_destroy()) {
$prompt = true;
}
break;
}
// 8. 结果返回前端
echo json_encode($prompt);
die;