博客列表 >会话控制 -(一)COOKIE/SESSION

会话控制 -(一)COOKIE/SESSION

CY明月归
CY明月归原创
2022年05月05日 08:06:19692浏览

COOKIE/SESSION原理:

作业:独立完成新用户注册的过程 ,并详细会话的完整流程,以及注意事项

  1. <?php
  2. //根据用户操作,给出不同响应
  3. //登录、注册、退出
  4. $dbConfig =[
  5. 'type'=>'mysql',
  6. 'host' => 'localhost',
  7. 'dbname' => 'testsql',
  8. 'port'=>'3306',
  9. 'charset'=>'utf8',
  10. 'username' => 'zolo',
  11. 'password' => '123456'
  12. ];
  13. //import variables into the current symbol table from an array
  14. extract($dbConfig);
  15. $db = new PDO("$type:host=$host;port=$port;dbname=$dbname;charset=$charset",$username,$password);
  16. $sqlquery = "select * from `user`";
  17. $stmt = $db->prepare($sqlquery);
  18. $stmt ->execute();
  19. $res = $stmt->fetchAll(PDO::FETCH_ASSOC);
  20. // foreach($res as $user){
  21. // printf('<pre>%s</pre>',print_r($user,true));}
  22. session_start();
  23. $method = $_GET['action'];
  24. switch(strtolower($method)){
  25. case 'login':
  26. if($_SERVER['REQUEST_METHOD']=='POST'){
  27. extract($_POST);
  28. //echo "登录信息是:".$username.'<br>';
  29. array_filter($res,function($user) use ($name,$password){
  30. if($user['name'] == $name && $user['password'] == $password){
  31. $_SESSION['name']= $name;
  32. exit('<script>alert("登录成功");location.href="home.php"</script>');
  33. }else{
  34. exit('<script>alert("用户名或密码错误");location.href="login.php"</script>');
  35. }
  36. });
  37. }else{
  38. echo '登录错误';
  39. }
  40. break;
  41. case 'register':
  42. if($_SERVER['REQUEST_METHOD']=='POST'){
  43. extract($_POST);
  44. if($password == $confirpsw){
  45. array_filter($res,function($user) use ($name,$password,$db){
  46. if($user['name'] == $name){
  47. //$_SESSION['name']= $name;
  48. exit('<script>alert("用户已存在,请登录");location.href="login.php"</script>');
  49. }else{
  50. if($name && $password){
  51. $sql = 'INSERT `user` SET `name` = ?,`password`= ?';
  52. $stmt = $db->prepare($sql);
  53. $stmt ->execute([$name,$password]);
  54. $_SESSION['name']= $name;
  55. exit('<script>alert("恭喜,注册成功");location.href="home.php"</script>');
  56. }else{
  57. exit('<script>alert("非法数据");location.href="register.php"</script>');
  58. }
  59. }
  60. });
  61. }else{
  62. exit('<script>alert("两次输入密码不一致");location.href="register.php"</script>');
  63. }
  64. }
  65. break;
  66. case 'logout':
  67. echo '设置session.name为空';
  68. session_unset();
  69. exit('<script>alert("退出成功");location.assign("home.php")</script>');
  70. break;
  71. }

代码流程图

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议