dqh19413
2013-09-03 13:38
浏览 47
已采纳

在脚本1中的脚本2中设置的访问会话变量.PHP

I have a loop that does some actions, within the loop I have a session counter that increments. It takes around 10-15 minutes for this loop to finish so I would like to have some kind of progress bar that tells user how far its gone through the loop.

My AJAX Call suppose to retrieve the value of the session that I set inside the loop but it does not seem to work. I get undefined index error.

I read somewhere that session gets locked once its used by one script and until it finishes using it, does not unlock it. Is it possible to force unlock on session so my ajax script can retrieve the value of session?

Example:

Script 1 (Loop):

while(SOME CONDITION) {
    //DO ACTIONS

    $_SESSION['progress'] = $currProgress + 1;
}

Script 2 (AJAX Call Retrieve Session):

function getCurrentProgress() {
   $progress = isset($_SESSION['progress']) ? $_SESSION['progress'] : 0;
   echo json_encode(array('progress' => $progress));
}

JS AJAX (calls every 30 seconds) to the above script

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • doujia4759 2013-09-03 13:46
    最佳回答

    PHP session changes aren't written to the session storage by default until the end of the program; while the program is running, $_SESSION is just like any other variable; only accessible within its own program; it's only when the program ends and the session is written to disk that the next program can get at the changes you've made to the session data. So the short answer is that you won't be able to do this just by checking the session and expecting the latest updates to be there.

    You can force PHP to write to the session at any time during the program by using the session_write_close() function, but as you may gather from the function name, this will also close the session to that program, so that program can't make any further updates to it.

    I guess you could then re-open the session, but that's starting to venture into dangerous territory. Even if it did work, it would be very inefficient.

    Ultimately, the PHP session is written to a file, just like any other output, but there are significant overheads to opening it and closing it repeatedly. So if you're considering the above, forget it -- you may as well just have your program write it's progress to a temp file or even a database. Or if you want performance, maybe use memcache.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题