Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
<?php
//链接数据库文件
require 'config/catenate.php';
//开启会话
session_start();
//查询用户数据
$stmt = $db->prepare('SELECT * FROM `user`;');
if ($stmt->execute()) {
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
print_r($stmt->errorInfo());
}
//判断请求类型
$action = strtolower($_GET['action']);
// print_r($action);
switch ($action) {
//登录
case 'login':
//判断是否为POST请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//获取用户登录传进的数据
$email = $_POST['email'];
$password = sha1($_POST['password']);
//从数据库中进行对比
$res = array_filter($users, function ($user) use ($email, $password) {
return $user['email'] === $email && $user['password'] === $password;
});
if (count($res) === 1) {
//写入session
$_SESSION['user'] = serialize(array_pop($res));
exit('<script>alert("登录成功");location.href="index.php";</script>');
} else {
exit('<script>alert("账户或密码错误,或者还没有帐号");location.href="login.php";</script>');
}
} else {
die('请求类型错误');
}
//注册
case 'reg':
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//获取用户注册传进的数据
$name = $_POST['name'];
$email = $_POST['email'];
$password = sha1($_POST['p1']);
$reg_time = time();
// 将数据写入数据库
// $sql = "INSERT `info` SET `biaoti`=:biaoti, `neirong` = :neirong, `time`= :sjtime ";
$sql = <<<SQL
INSERT `user`
SET `name`= ?,
`email` = ?,
`password` = ?,
`reg_time` = ?
SQL;
$stmt = $db->prepare($sql);
$data = [$name, $email, $password, $reg_time];
$stmt->execute($data);
if ($stmt->rowCount() === 1) {
$sql = 'SELECT * FROM `user` WHERE `id` = ' . $db->lastInsertId();
$stmt = $db->prepare($sql);
$stmt->execute();
$newUser = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['user'] = serialize($newUser);
exit('<script>alert("注册成功");location.assign("index.php")</script>');
} else {
exit('<script>alert("注册失败");location.assign("login.php")</script>');
}
}
//退出
case 'logout':
if (isset($_SESSION['user'])) {
session_destroy();
exit('<script>alert("退出成功");location.assign("index.php")</script>');
}
default:
exit('未定义的操作');
}