如何从 SESSID 获取 $_SESSION 数据? [英] How can I get $_SESSION data from SESSID?

查看:47
本文介绍了如何从 SESSID 获取 $_SESSION 数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 PHP websocket 服务器 (https://github.com/lemmingzshadow/php-websocket/).

I have a PHP websocket server (https://github.com/lemmingzshadow/php-websocket/).

当用户连接时,我想设置/获取一些会话数据.

When an user connects, I want to set/get some session data.

问题是我不能使用 $_SESSION 因为如果我这样做,我会得到我的 websocket 服务器的会话而不是客户端的会话.

The problem is that I can't use $_SESSION because if I do that, instead of clients' session I get the session of my websocket server.

我已设法获得客户的 SESSID:

I have managed to get clients' SESSID:

private function handshake($data) { 
    $this->log('Performing handshake');  
    if(preg_match("/PHPSESSID=(.*?)(?:;|\r\n)/", $data, $matches)){
        $sessid = $matches[1];
    }
    /* Do handshake */
}

但现在我不知道如何获取与该 SESSID 相关的会话数据.

But now I don't know how to get the session data related to that SESSID.

推荐答案

看来我已经解决了(但我还要多测试):

It seems I have solved it (but I have to test it more):

private function handshake($data) { 
    $this->log('Performing handshake');
    if(preg_match("/PHPSESSID=(.*?)(?:;|\r\n)/", $data, $matches)){
        $this->sessID = $matches[1];
        session_id($this->sessID);
        @session_start();
        if(isset($_SESSION['userName'])){
            $this->userName = $_SESSION['userName'];
        }else{
            $_SESSION['userName'] = $this->userName;
        }
        session_write_close();
    }else{
        $this->log('No SESSID');    
        return false;
    }
    /* Do handshake */
}

并在我的客户端页面 index.php 上启用会话 cookie

And to enable session cookies, on my client page index.php

<?php
session_start();
?>
<!DOCTYPE html>
<!-- Page's HTML -->

说明

首先,我使用 session_id 以便以下 session_start() 会给我相关的会话给定的 SESSID.

First, I use session_id so that the following session_start() will give me the session related to the given SESSID.

然后,我可以使用 @session_start() 开始会话.它需要 @ 因为 websocket 服务器已经启动,所以不需要使用它产生:

Then, I can use @session_start() to start the session. It needs @ because the websocket server has already started, so not using it produces:

  • PHP 警告:session_start():无法发送会话 cookie - 标头已发送
  • PHP 警告:session_start():无法发送会话缓存限制器 - 标头已发送

现在我可以用 $_SESSION 做我想做的事.

Now I can do what I want with $_SESSION.

最后,我使用 session_write_close() 以关闭会话.必须使用它,因为:

Finally, I use session_write_close() in order to close the session. It must be used because:

为了避免会话锁定.正如@Sven 所说,只能有一个 PHP 实例可以访问会话文件.由于websocket服务器的脚本要运行很长时间,一旦打开一个session,不关闭就不能在其他脚本中使用session.

To avoid session locking. As @Sven said, there can only be one instance of PHP running that has access to the session file. Since the websocket server's script should be running for a long time, once it opens a session, you can't use session in other scripts if you don't close it.

这篇关于如何从 SESSID 获取 $_SESSION 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆