helloxielan 2018-03-27 14:01 采纳率: 0%
浏览 40

Ajax重置PHP会话

I know this question has been asked before so I apologize ahead of time, but I have gone over his solution multiple times and it does not fix the session reset in my case.

I have a simple php page that outputs a session id for debugging. Like this:

<?php
session_start();
echo session_id();
?>

Then I have a simple HTML page with jQuery that performs an ajax request on that page and logs the output.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
      $.post('http://localhost.api.mydomain/sid', {
        some: 'data'
      }, function(data,status) {
        console.log(data);
      });
    </script>
  </head>
  <body>
    Check your console.
  </body>
</html>

If I manually visit the url http://localhost.api.mydomain/sid the output never changes, the session_id() stays constant, as expected. However, if I refresh the ajax page, the outputted session_id() changes with every refresh.

I've tried setting session.cookie_domain in the php.ini file but to no avail. I apologize for this issue, but I simply cannot find a solution.

  • 写回答

2条回答 默认 最新

  • weixin_33730836 2018-03-27 14:55
    关注

    The reason is because the ajax request does not send the session id along with the request. That causes session_start to generate a new one.

    Possible reason that could make the browser not send the session cookie during the ajax request is discrepancy in domain name.

    instead of setting session.cookie_domain on the ini file, set it as follows at runtime

    session_set_cookie_params(33600, '/', 'localhost.api.mydomain', FALSE, TRUE);
    session_start();
    

    To help you debug this, go to network tab on the developers tools in chrome. reload the page and check the request headers and response headers. check the host to which jquery sends the request. it may be sending the request to just localhost. and you may have configured your site to accept both localhost and localhost.api.mydomain.

    to do more check, in your file, do something like

    session_set_cookie_params(33600, '/', 'localhost.api.mydomain', FALSE, TRUE);
    session_start();
    die($_SERVER['HTTP_HOST']);
    

    this will let you compare the request url used by jquery during the ajax request.

    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?