PHP实现简单请求分发器的注册与退出登录。
发布于:2022-02-15 10:21:29
次阅读
简单请求分发器的注册与退出登录
<?phpreturn [ 'type' => $type ?? 'mysql', 'username' => $username ?? 'root', 'password' => $password ?? '', 'host' => $host ?? 'localhost', 'port' => $port ?? '3306', 'charset' => $charset ?? 'utf8', 'dbname' => 'user'];
// 1. 把数据库连接配置文件引过来$config = require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'database.php';extract($config);// 2. 数据库的连接$dsn = sprintf('%s:host=%s;port=%s;charset=%s;dbname=%s', $type, $host, $port, $charset, $dbname);try { $pdo = new PDO($dsn, $username, $password); // var_dump($pdo);} catch (PDOException $e) { die('Connection error : ' . $e->getMessage());}
- 3.建立,dosubmit.php对前端请求,进行分发处理。
<?php// 控制器文件require 'common.php';// 后端可接受前端传过来的参数$name = isset($_POST['uname']) ? $_POST['uname'] : null;$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : null;$type = strtolower($_GET['type']);var_dump($name, $pwd, $type);// 请求分发器 注册 登录 退出登录switch ($type) { case 'login': $res = checkName($name, $pwd); if ($res) { echo json_encode(['status' => 1, 'msg' => '登录成功'], 320); exit; } echo json_encode(['status' => 0, 'msg' => '用户名或密码错误'], 320); break; case 'logout': echo json_encode(['status' => 0, 'msg' => '退出登录'], 320); header("location:./2-login.php"); session_destroy(); break; case 'reg': $res = regusername($name, $pwd); if ($res) { echo json_encode(['status' => 1, 'msg' => '注册成功'], 320); exit; } echo json_encode(['status' => 0, 'msg' => '注册失败'], 320); break; // // 插入 // case :'logout':}
<?phpsession_start();// 模型文件 model//连接数据库require '1-connect.php';function checkName($name, $pwd){ $sql = "SELECT `username`,`password` FROM `user` WHERE `username` = ? AND `password` = ? "; // prepare准备阶段 global $pdo; $stmt = $pdo->prepare($sql); $res = $stmt->execute([$name, $pwd]); if ($res) { $res = $stmt->fetch(PDO::FETCH_ASSOC); // 验证通过 if ($res) { $_SESSION['username'] = $res['username']; return true; } else { return false; } }}function regusername($name, $pwd){ $sql = "SELECT `username`,`password` FROM `user` WHERE `username` = ?"; $sql_reg="INSERT INTO 'user'('username','password') VALUES (?,?)"; global $pdo; $stmt = $pdo->prepare($sql); $res = $stmt->execute([$name]); if ($res) { $res = $stmt->fetch(PDO::FETCH_ASSOC); if ($res) { //已存在用户 返回注册失败 return false; } else { $stmt = $pdo->prepare($sql_reg); $stmt->debugDumpParams($sql_reg); $res = $stmt->execute([$name,$pwd]); if ($res) { $res = $stmt->fetch(PDO::FETCH_ASSOC); if ($res) { return true; } else { var_dump("注册失败1"); return false; } } var_dump("注册失败2"); return false; } }}