donglian8407 2015-05-11 17:50
浏览 22
已采纳

检查会话是否仍在运行的正确方法是什么? 有哪些方法?

So I have already had my first experience with Web Design, but there were some things I did in a certain way that I didn't like, mainly because of time. So anyway, I don't know which is the correct way to handle sessions. What I did in my previous project was to embed PHP into HTML and based on whatever was in $_SESSION, usually an id and a user type number, then I'd open or close parts of the website to the user, through embedded PHP.

However, this is not how I wanted to do this initially, at first what I wanted to do was to make a JavaScript code to send a request through AJAX to the server, and check if the session was still active, and based on that open/close parts of the website, but then I'd have to make a request on every page and every so often to make sure the user is logged in. Should I handle something like this client-side?

What are some other ways to check the session but without embedding PHP and using JavaScript instead to modify the HTML document.

  • 写回答

1条回答 默认 最新

  • dsaff82024 2015-05-11 18:04
    关注

    To do this, all you need is an ajax request on loop and a php file to check the session.

    The Javascript

    function checkLogin(un) { //put this function in a loop of some sort depending on how you want to use it
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          logout(xmlhttp.responseText);
        }
      }
      xmlhttp.open("GET", "checklogin.php?un=" + un, true);
      xmlhttp.send();
    }
    
    function logout(resp) {
      if (resp == "false") { //comparing actual text, not boolean
        window.location.href = 'logout.php'; //destroy the session or something
      }
    }
    

    The PHP file checklogin.php (very simple)

    <?php
    if ($_SESSION[$_GET['un']] != true) {
      echo 'false';
    }
    ?>
    

    The php will depend on how you store your sessions, but in this case it is just using one session titled by their username that stores true if signed in. I would recommend making this more complex if you decide to actually use it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大