Blogger Information
Blog 33
fans 0
comment 0
visits 19503
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
11月22日作业SESSION 登录实战--php培训九期线上班
取个名字真难
Original
785 people have browsed it

index.phph文件

  1. <?php
  2. //开启会话
  3. session_start();
  4. var_dump( $_SESSION['name']);
  5. if(isset($_SESSION['name']) && $_SESSION['name']==='admin'){
  6. echo '用户:'.$_SESSION['name'].'已登录';
  7. echo '<a href="dispatch.php?action=logout">请登录</a>a>';
  8. }else{
  9. // 未登录
  10. echo '没有登录';
  11. echo '<a href="login.php">请登录</a>';
  12. }

login.php

  1. <?php
  2. // 防止用户重复登录
  3. if (isset($_SESSION['name'])) {
  4. echo '不要重复登录';
  5. require __DIR__.'/index.php';
  6. }
  7. ?>
  8. <!doctype html>
  9. <html lang="en">
  10. <head>
  11. <meta charset="UTF-8">
  12. <title>用户登录</title>
  13. </head>
  14. <form method="POST" action="check.php">
  15. <label for="name">手机号:</label><br>
  16. <input type="phone" name="phone" id="phone"><br>
  17. <label for="password">密码:</label><br>
  18. <input type="password" name="password" id="password"><br>
  19. <button>提交</button>
  20. </form>
  21. </body>
  22. </html>

check.php

  1. <?php
  2. session_start();
  3. //链接数据库
  4. require __DIR__ .'/connect.php';
  5. // 1.判断用户的请求类型是否正确?
  6. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  7. // 2.获取表单数据
  8. $phone = $_POST['phone'];
  9. $password = sha1($_POST['password']);
  10. // 3. 用用户表user.dbf进行验证
  11. $sql = 'SELECT * FROM `user` WHERE `phone` = :phone';
  12. $stmt = $pdo->prepare($sql);
  13. $stmt->execute();
  14. $user = $stmt->fetch(PDO::FETCH_ASSOC);
  15. // 4. 判断验证的结果
  16. if (false === $user) {
  17. // 验证失败,返回上一下页面
  18. echo '<script>alert("验证失败");history.back();</script>';
  19. die;
  20. }
  21. echo $user['phone'];
  22. // 验证成功,将用户的信息写到session
  23. $_SESSION['name'] = $user['name'];
  24. echo '<script>alert("登录成功");location.assign("index.php");</script>';
  25. exit;
  26. } else {
  27. die('请求类型错误');
  28. }

这里验证总是失败一直找不到原因

logout.php

  1. <?php
  2. // 必须在用户已经登录的情况下再退出
  3. if (isset($_SESSION['name'])) {
  4. session_destroy();
  5. echo '退出成功';
  6. } else {
  7. // 要求用户先登录
  8. echo '<script>alert("请先登录");location.assign("login.php");</script>';
  9. }



Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:session与cookie的应用场景不同, session同样也是基于cookie才能工作,他们二者配合才能完成目标
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!