将请求分发器的注册与退出登录完善
程序员文章站
2022-03-07 18:11:36
...
<?php
session_start();
//连接数据库
require '1-connect.php';
// 接受前端传过来的参数
$name = isset($_POST['uname']) ? $_POST['uname'] : null;
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : null;
$gender = isset($_POST['gender']) ? $_POST['gender'] : null;
$created_at = time();
$type = strtolower($_GET['type']);
// 请求分发器 注册 登录 退出
switch ($type) {
case 'login':
$res = loginCheck($name, $pwd);
if ($res) {
echo json_encode(['status' => 1, 'msg' => '登录成功'], 320);
exit;
}
echo json_encode(['status' => 0, 'msg' => '用户名或密码错误'], 320);
break;
case 'reg':
$res = insertData($name, $pwd, $gender, $created_at);
if ($res) {
echo json_encode(['status' => 1, 'msg' => '注册成功'], 320);
exit;
}
echo json_encode(['status' => 0, 'msg' => '注册失败'], 320);
break;
case 'logout':
session_destroy();
header('Location:index.php');
break;
default:
exit('非法请求');
}
function loginCheck($name, $pwd)
{
global $pdo;
$sql = "SELECT `username`,`password` FROM `user` WHERE `username` = ? AND `password` = ? ";
$stmt = $pdo->prepare($sql);
$res = $stmt->execute([$name, md5($pwd)]);
if ($res) {
$res = $stmt->fetch(PDO::FETCH_ASSOC);
if ($res) {
$_SESSION['username'] = $res['username'];
return true;
} else {
return false;
}
}
}
function insertData($name, $pwd, $gender, $created_at)
{
global $pdo;
$flag = false;
$sql = "INSERT INTO `user` SET `username` =?,`password`=?, `gender`=?,`created_at`=? ";
$stmt = $pdo->prepare($sql);
$stmt->execute([$name, $pwd, $gender, $created_at]);
if ($stmt->rowCount() == 1) {
$flag = true;
}
return $flag;
}
?>