注册、登陆、退出请求分发器实例
程序员文章站
2022-04-17 18:46:39
...
注册、登陆、退出请求分发器实例代码
<?php
session_start();
// 后端可接受前端传过来的参数
$name = isset($_POST['username']) ? $_POST['username'] : null;
$pwd = isset($_POST['password']) ? $_POST['password'] : null;
$pwd2 = isset($_POST['password2']) ? $_POST['password2'] : null;
$action = isset($_POST['action']) ? $_POST['action'] : null;
if ($action == ''){
$action = isset($_GET['action']) ? $_GET['action'] : null;
}
// 1.连接数据库
$config = require_once __DIR__ .DIRECTORY_SEPARATOR .'connect.php';
// var_dump($config);
// pdo预处理接入
// 准备一条预处理sql语句
$sql = "SELECT `username`,`password` FROM `users` WHERE `username`= ?;";
// 准备要执行的语句,并返回语句对象
$stmt = $pdo->prepare($sql);
// 绑定参数到指定的变量名
$para = [$name];
// 执行一条预处理语句
$stmt->execute($para);
$res = $stmt->fetch(PDO::FETCH_ASSOC);
// echo '<pre>';
// print_r($res);
switch ($action){
case 'login':
if(empty($res)){
echo json_encode(array('code'=>2, 'msg'=>'用户名不存在。'));
}else{
if(password_verify($pwd, $res['password'])){
echo json_encode(array('code'=>1, 'msg'=>'登录成功'));
$_SESSION['username'] = $res['username'];
return true;
}else {
echo json_encode(array('code'=>2, 'msg'=>'用户名或密码不正确。'));
}
}
break;
case 'register':
if(!empty($res)){
echo json_encode(array('code'=>2, 'msg'=>'用户名已存在。'));
}else{
if($pwd == $pwd2){
$pwd = password_hash ($pwd,PASSWORD_DEFAULT );
$sql = "INSERT INTO `users` (`username`, `password`) VALUES (?, ?);";
$stmt = $pdo->prepare($sql);
// 绑定参数到指定的变量名
$para = [$name,$pwd];
// 执行一条预处理语句
$stmt->execute($para);
$insert_id = $pdo->lastInsertId();
if($insert_id){
echo json_encode(array('code'=>1, 'msg'=>'登录成功'));
}else {
echo json_encode(array('code'=>2, 'msg'=>'用户名或密码不正确。'));}
}else{
echo json_encode(array('code'=>2, 'msg'=>'两次输入密码不一致。'));
};
};
break;
case 'logout':
session_destroy();
echo json_encode(array('code'=>1, 'msg'=>'退出成功。'));
break;
}