Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
用户登录、注册、退出,我们主要是为了演示 cookie
和 session
的使用方法。
$action = strtolower($_GET['action']);
switch ($action){
case 'login':
if($_SERVER['REQUEST_METHOD'] === 'POST'){
$email = $_POST['email'];
$password= sha1($_POST['password']);
//echo $password;
//die ($email);
$result = array_filter($users, function ($user) use ($email,$password){
return $user['email'] === $email && $user['password'] === $password;
});
//
if (count($result) === 1){
$_SESSION['user'] = serialize(array_pop($result));
exit ('<script>alert("验证通过");location.href="index.php"</script>');
}
exit ('请求类型错误');
}
case 'logout':
if (isset($_SESSION['user'])){
session_destroy();
exit ('<script>alert("退出成功");location.href="index.php"</script>');
}
case 'register':
$email = $_POST['email'];
$name= $_POST['name'];
$password= sha1($_POST['p2']);
$register_time = time();
$sql = <<< SQL
INSERT `user`
SET `name` = ?,
`email` = ?,
`password` = ?,
`register_time` = ?;
SQL;
$stmt = $db->prepare($sql);
$data = [$name,$email,$password, $register_time];
if ($stmt->execute($data)) {
if ($stmt->rowCount() > 0) {
$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.href="index.php"</script>');
}else{
exit ('<script>alert("注册失败");location.href="register.php"</script>');
}
}else{
print_r($stmt->errorInfo());
}
default;
exit('参数非法或未定义操作');
}