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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘