博客列表 >PHP会话控制session和cookie

PHP会话控制session和cookie

滑稽...
滑稽...原创
2020年05月11日 10:16:53595浏览

1、数据保存在客户端浏览器上,如果浏览器关闭cookie,则无法使用
2、创建cookie:setcookie(名称,值,[过期时间])
3、使用cookie:$_COOKIE[‘名称’]
4、删除cookie:为cookie设置一个已经过期的时间,如:setcookie(名称,值,time()-1)

SESSION

1、数据保存在服务器上
2、启动session:session_start()
3、创建session:$_SESSION[‘名称’]=值
4、使用session:$_SESSION[‘名称’]
5、删除单个session:unset($_SESSION[‘名称’])
6、删除所有的session:session_unset()
7、销毁session:session_destory()


handle.php

  1. <?php
  2. //echo phpinfo();
  3. // 开启会话
  4. session_start();
  5. // 查询用户表中的数据
  6. $pdo = new PDO('mysql:host=localhost;dbname=phpedu','root','root');
  7. $sql = 'SELECT * FROM `user`';
  8. $stmt = $pdo->prepare($sql);
  9. $stmt->execute();
  10. $users = $stmt->fetchALL(PDO::FETCH_ASSOC);
  11. // 处理用户登录与注册
  12. $action = $_GET['action'];
  13. switch(strtolower($action))
  14. {
  15. case 'login':
  16. // 判断请求是否合t法
  17. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  18. // 获取需要验证的数据
  19. $email = $_POST['email'];
  20. $password = sha1($_POST['password']);
  21. //array_filter(): 用回调过滤数组中的单元,返回计算结果为true的元素组成的数组
  22. //判断验证的邮箱和密码是否在数据库中存在
  23. $results = array_filter($users, function($user) use ($email, $password) {
  24. return $user['email'] === $email && $user['password'] === $password;
  25. });
  26. if (count($results) === 1) {
  27. //将身份信息序列化存到session中
  28. $_SESSION['user'] = serialize(array_pop($results));
  29. //将身份信息序列化存到cookie中
  30. //setcookie('user', serialize(array_pop($results)));
  31. exit('<script>alert("验证通过");location.href="index.php"</script>');
  32. } else {
  33. exit('<script>alert("邮箱或密码错误,或者还没有帐号");location.href="login.php";</script>');
  34. }
  35. } else {
  36. die('请求类型错误');
  37. }
  38. break;
  39. case 'logout' :
  40. if(isset($_SESSION['user'])){
  41. unset($_SESSION);
  42. session_destroy();
  43. setcookie('user','',time()-3600);
  44. //将身份信息从cookie中删除
  45. //setcookie('user', null , time()-3600);
  46. }
  47. break;
  48. case 'register' :
  49. if($_SERVER['REQUEST_METHOD'] == 'POST'){
  50. $data['name'] = $_POST['name'];
  51. $data['email'] = $_POST['email'];
  52. $data['password'] = $_POST['p1'];
  53. $data['add_time'] = time();
  54. //注册前判断数据库只是否存在重复的邮箱
  55. $results = array_filter($users,function ($user) use($email){
  56. if($user['email'] == $email){
  57. return false;
  58. }else{
  59. return true;
  60. }
  61. });
  62. // $keys = array_keys($data);
  63. // $values = array_values($data);
  64. // array_walk($keys,function (&$item,$key){
  65. // $item = "`$item`";
  66. // });
  67. // array_walk($values,function (&$item,$key){
  68. // $item = "'$item'";
  69. // });
  70. //将获取到的数据封装成sql语句
  71. $keys = [];
  72. $values = [];
  73. array_walk($data,function ($item,$key){
  74. $keys[] = "`$key`";
  75. $values[] = "'$item'";
  76. });
  77. $keys = implode(',',$keys);
  78. $values = implode(',',$values);
  79. if($results){
  80. $sql = "INSERT `user` ($keys) VALUES ($values)";
  81. $stmt = $pdo->prepare($sql);
  82. $stmt->execute();
  83. if($stmt->rowCount() ===1)exit('<script>alert("注册成功");location.assign("login.php")</script>');
  84. else exit('<script>alert("注册失败");location.assign("login.php")</script>');
  85. break;
  86. }
  87. }else{
  88. die('请求类型错误');
  89. }
  90. }

index.php

  1. <?php
  2. // 开启会话
  3. session_start();
  4. // 判断是否已经登录?
  5. if (isset($_SESSION['user'])) $user = unserialize($_SESSION['user']);
  6. ?>
  7. <!DOCTYPE html>
  8. <html lang="en">
  9. <head>
  10. <meta charset="UTF-8">
  11. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  12. <link rel="stylesheet" type="text/css" href="./css/index.css">
  13. <title>首页</title>
  14. </head>
  15. <body>
  16. <nav>
  17. <a href="index.php">我的论坛</a>
  18. <?php if (isset($user)) : ?>
  19. <a href="" id="logout"><span style="color:red"><?php echo $user['name']?></span>&nbsp;&nbsp;退出</a>
  20. <?php else: ?>
  21. <a href="login.php">登录</a>
  22. <?php endif ?>
  23. </nav>
  24. </body>
  25. <script>
  26. // 为退出按钮创建事件监听器
  27. document.querySelector('#logout').addEventListener('click', function(event) {
  28. if (confirm('是否退出')) {
  29. // 禁用默认行为, 其实就是禁用原<a>标签的点击跳转行为,使用事件中的自定义方法处理
  30. event.preventDefault();
  31. // 跳转到退出事件处理器
  32. window.location.assign('handle.php?action=logout');
  33. }
  34. });
  35. </script>
  36. </html>

login.php

  1. <?php
  2. // 开启会话
  3. session_start();
  4. // 判断是否已登录
  5. if (isset($_SESSION['user']))
  6. exit('<script>alert("请不要重复登录");location.href="index.php";</script>');
  7. ?>
  8. <!DOCTYPE html>
  9. <html lang="en">
  10. <head>
  11. <meta charset="UTF-8">
  12. <title>用户登录</title>
  13. <link rel="stylesheet" type="text/css" href="./css/style.css?1.0">
  14. </head>
  15. <body>
  16. <h3>用户登录</h3>
  17. <form action="handle.php?action=login" method="post">
  18. <div>
  19. <label for="email">邮箱:</label>
  20. <input type="email" name="email" id="email" placeholder="demo@email.com" required autofocus>
  21. </div>
  22. <div>
  23. <label for="password">密码:</label>
  24. <input type="password" name="password" id="password" placeholder="不少于6位" required>
  25. </div>
  26. <div>
  27. <button>提交</button>
  28. </div>
  29. </form>
  30. <a href="register.php">还没有帐号, 注册一个吧</a>
  31. </body>
  32. </html>

register.php

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <link rel="stylesheet" type="text/css" href="./css/style.css">
  7. <title>注册用户</title>
  8. </head>
  9. <body>
  10. <h3>用户注册</h3>
  11. <form action="handle.php?action=register" method="post" onsubmit="return compare()">
  12. <div>
  13. <label for="name">呢称:</label>
  14. <input type="text" name="name" id="name" placeholder="不少于3个字符" required autofocus>
  15. </div>
  16. <div>
  17. <label for="email">邮箱:</label>
  18. <input type="email" name="email" id="email" placeholder="demo@email.com" required>
  19. </div>
  20. <div>
  21. <label for="p1">密码:</label>
  22. <input type="password" name="p1" id="p1" placeholder="不少于6位" required>
  23. </div>
  24. <div>
  25. <label for="p2">重复:</label>
  26. <input type="password" name="p2" id="p2" placeholder="必须与上面一致" required>
  27. </div>
  28. <div>
  29. <button>提交</button><span id="tips" style="color: red"></span>
  30. </div>
  31. </form>
  32. <a href="login.php">我有帐号,直接登录</a>
  33. <script>
  34. // 验证二次密码是否相等?
  35. function compare() {
  36. if (document.forms[0].p1.value.trim() !== document.forms[0].p2.value.trim()) {
  37. document.querySelector('#tips').innerText = '二次密码不相等';
  38. return false;
  39. }
  40. }
  41. </script>
  42. </body>
  43. </html>
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议