Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在Ratchet websocket应用程序中将旧会话($\u会话)与symfony会话一起使用_Php_Symfony_Session_Websocket - Fatal编程技术网

Php 如何在Ratchet websocket应用程序中将旧会话($\u会话)与symfony会话一起使用

Php 如何在Ratchet websocket应用程序中将旧会话($\u会话)与symfony会话一起使用,php,symfony,session,websocket,Php,Symfony,Session,Websocket,好吧,让我先说我不是框架的狂热粉丝。我已经使用遗留会话(login.php)开发了我的应用程序: 当我将$conn->Session->all()输出到终端时,我得到一个警告PHP警告:SessionHandler::open():会话未激活以及一个空数组,当我将$\u Session输出到终端时,我得到: array(3) { ["_sf2_attributes"]=> &array(0) { } ["_symfony_flashes"]=> &

好吧,让我先说我不是框架的狂热粉丝。我已经使用遗留会话(login.php)开发了我的应用程序:

当我将
$conn->Session->all()
输出到终端时,我得到一个警告
PHP警告:SessionHandler::open():会话未激活
以及一个空数组,当我将
$\u Session
输出到终端时,我得到:

 array(3) {
  ["_sf2_attributes"]=>
  &array(0) {
  }
  ["_symfony_flashes"]=>
  &array(0) {
  }
  ["_sf2_meta"]=>
  &array(3) {
    ["u"]=>
    int(1518882401)
    ["c"]=>
    int(1518882401)
    ["l"]=>
    string(1) "0"
  }
}
我没有得到任何会话数据,我尝试使用其他会话处理程序,如
MemcacheSessionHandler、MemcachedSessionHandler、PdoSessionHandler
,但它们都将会话保留为空,我尝试过其他存储类,但symfony文档建议在您希望将旧会话与symfony会话集成时使用
PhpBridgeSessionStorage

我知道有推送通知框架,但我不想使用它们的第三方服务


我已经研究了好几天了,我找不到任何有用的东西。

如果你不喜欢像我这样的框架,那么我猜这个答案可以帮助你。实际上,我在WebSocket上找不到任何关于如何将Symfony会话与遗留会话($\u会话)结合使用的好文档。大多数教程和线程建议在整个应用程序中单独使用Symfony会话。。。但是,如果您喜欢我,并且在您的大部分应用程序中已经使用了遗留会话,那么您可以尝试此替代方案

摆脱symfony会话代码和ratchet会话提供程序,这就是my server.php现在的样子:

<?php
require 'vendor/autoload.php';
require 'include/connect.php';
include 'models/Notify.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Ratchet\App;
use Notify\Notification;


try{
    $domain = '127.0.0.1';

    $server = IoServer::factory(
        new HttpServer(
            new WsServer(
                new Notification
            )
        ),
        3002,
        $domain
    );

    $server->run();

}catch(Exception $e){
    echo "Error: {$e->getMessage()}";
}
一旦有了它,您就可以通过设置会话id
session\u id($sessiond)
在websocket服务器上使用它来设置会话,但为了避免我在这样做时遇到的问题,我建议您在用户登录后将PHPSESSID存储在数据库中。。。此id应唯一,以防止冲突。不要使用
会话\u重新生成\u id()
,请使用
会话\u创建\u id()
。因此,在WebSocket服务器上,您将运行一个查询来获取您拥有PHPSESSID的用户的信息。我建议像这样创建会话类:

<?php
namespace Library;
class _Session {
    private $sess_id;
    private $session;

    public function __construct(array $cookies){
        include 'include/connect.php';
        foreach($cookies as $cookie):
            if(strpos($cookie, "PHPSESSID") == 0):
                $this->sess_id = explode('=', $cookie)[1];
                break;
            endif;
        endforeach;
        $query = "SELECT * FROM general_user WHERE sess_id = ?";

        $query_run = $database->prepare($query);

        if($query_run->execute([$this->sess_id])):
            if($query_run->rowCount() == 1):
                $query = "SELECT g.id, g.email, u.username, u.firstname, u.lastname, g.about_me, u.gender, p.name AS profile_pic, 'u' AS user_type FROM general_user g INNER JOIN userdata u ON u.id = g.id LEFT JOIN profile_photo p ON g.id = p.user_id WHERE sess_id = ?";

                $query_run = $database->prepare($query);

                if($query_run->execute([$this->sess_id])):
                    if($query_run->rowCount() == 0):
                        $query = "SELECT g.id, g.email, g.about_me AS company_description, c.category, c.subcategory, c.company_name, c.contact_num, c.website, p.name AS profile_pic, 'c' AS user_type FROM general_user g INNER JOIN companydata c ON c.id = g.id LEFT JOIN profile_photo p ON g.id = p.user_id WHERE sess_id = ?";

                        $query_run = $database->prepare($query);

                        if($query_run->execute([$this->sess_id])):
                            $this->session = $query_run->fetchAll()[0];
                        endif;
                    else:
                        $this->session = $query_run->fetchAll()[0];
                    endif;
                endif;
            else:
                $this->session = [];
            endif;
        endif;

    }

    function get($key){
        foreach($this->session as $k => $value)
            if($key == $k)
                return $value;
        throw new \Exception("Undefined index $key");
    }
}

Symfony已经在使用$\u会话。它以不同的方式被同步访问。。。为什么您拒绝在Symfony框架中使用它?如果您不想要框架的功能,请不要使用框架。。。我签出了该链接,但我更愿意这样设置会话:
$\u会话['usename']='bill'
,然后像这样访问它:
$conn->session->get('username')
。如果有一种不使用Symfony就可以访问会话数据的方法,那么@PrecielWell就太棒了,我想这是可能的,但我不建议这样做。。。Symfony确实创建了一个会话,甚至可能会覆盖您的会话……我已经尝试了所有方法,但除了最初使用Symfony设置会话之外,我似乎无法使用Symfony会话获取会话数据。
 array(3) {
  ["_sf2_attributes"]=>
  &array(0) {
  }
  ["_symfony_flashes"]=>
  &array(0) {
  }
  ["_sf2_meta"]=>
  &array(3) {
    ["u"]=>
    int(1518882401)
    ["c"]=>
    int(1518882401)
    ["l"]=>
    string(1) "0"
  }
}
<?php
require 'vendor/autoload.php';
require 'include/connect.php';
include 'models/Notify.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Ratchet\App;
use Notify\Notification;


try{
    $domain = '127.0.0.1';

    $server = IoServer::factory(
        new HttpServer(
            new WsServer(
                new Notification
            )
        ),
        3002,
        $domain
    );

    $server->run();

}catch(Exception $e){
    echo "Error: {$e->getMessage()}";
}
function getPHPSESSID(array $cookies){
    foreach($cookies as $cookie):
        if(strpos($cookie, "PHPSESSID") == 0):
            $sess_id = explode('=', $cookie)[1];
            break;
        endif;
    endforeach;
    return $sess_id;
}
<?php
namespace Library;
class _Session {
    private $sess_id;
    private $session;

    public function __construct(array $cookies){
        include 'include/connect.php';
        foreach($cookies as $cookie):
            if(strpos($cookie, "PHPSESSID") == 0):
                $this->sess_id = explode('=', $cookie)[1];
                break;
            endif;
        endforeach;
        $query = "SELECT * FROM general_user WHERE sess_id = ?";

        $query_run = $database->prepare($query);

        if($query_run->execute([$this->sess_id])):
            if($query_run->rowCount() == 1):
                $query = "SELECT g.id, g.email, u.username, u.firstname, u.lastname, g.about_me, u.gender, p.name AS profile_pic, 'u' AS user_type FROM general_user g INNER JOIN userdata u ON u.id = g.id LEFT JOIN profile_photo p ON g.id = p.user_id WHERE sess_id = ?";

                $query_run = $database->prepare($query);

                if($query_run->execute([$this->sess_id])):
                    if($query_run->rowCount() == 0):
                        $query = "SELECT g.id, g.email, g.about_me AS company_description, c.category, c.subcategory, c.company_name, c.contact_num, c.website, p.name AS profile_pic, 'c' AS user_type FROM general_user g INNER JOIN companydata c ON c.id = g.id LEFT JOIN profile_photo p ON g.id = p.user_id WHERE sess_id = ?";

                        $query_run = $database->prepare($query);

                        if($query_run->execute([$this->sess_id])):
                            $this->session = $query_run->fetchAll()[0];
                        endif;
                    else:
                        $this->session = $query_run->fetchAll()[0];
                    endif;
                endif;
            else:
                $this->session = [];
            endif;
        endif;

    }

    function get($key){
        foreach($this->session as $k => $value)
            if($key == $k)
                return $value;
        throw new \Exception("Undefined index $key");
    }
}
<?php
namespace Notify;
require __DIR__.'/../vendor/autoload.php';
include __DIR__.'/../classes/CustomSession.php';

use Library\_Session;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage;

class Notification implements MessageComponentInterface{
    protected $clients;

    function __construct(){
        $this->clients = [];
        echo "WebSocket Server Running...\n";
    }

    public function onOpen(ConnectionInterface $conn){
        $session = new _Session($conn->httpRequest->getHeader('Cookie'));//My custom session

        if($session->get('user_type') == 'u'){
            echo $session->get('username')." has connected\n";
        }else{
            echo $session->get('company_name')." has connected\n";
        }

        array_push($this->clients, ['connection' => $conn, 'session'=> $session]);


    }
}