PdoSessionHandler Mysql Sessions

1,250 views
Skip to first unread message

Leonardo Pucci

unread,
May 3, 2014, 1:04:44 PM5/3/14
to ratch...@googlegroups.com
I am posting this info based on my difficult to create a PdoHandler and learn how to use Symfony2

I did not want to use it, so I realized that Chris just grabbed some part of it, not entire framework. And used just the session part. 
I think this is relevant to explain, because sometimes you just don´t want to add more complexity to your code and think: OMG, another framework to understand, deploy, support, etc.
In the ratchet case, and if you only use the parts that Chris grabbed, you don´t need to much to understand. 

After a terrible goggling on info, I just opened SessionProvider.php and found it very instructive and well commented. 

So i am posting my ratchet start, so others could stop suffering two. 

I am using Mysql, as I am used to it. But wondering how to get rid of the blocking calls, didn´t figured out yet.

use Ratchet\WebSocket\WsServer;
use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;
use MyApp\Chat;
use Ratchet\Session\SessionProvider;
use Symfony\Component\HttpFoundation\Session\Storage\Handler;


    require dirname(__DIR__) . '/vendor/autoload.php';

$pdo = new PDO('mysql:host=localhost;dbname=DATABASE_NAME', 'MYSQL_USER', 'MYSQL_PASSWORD');

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

//This info is related to you db
$dbOptions = array(
    'db_table'      => 'session',
    'db_id_col'     => 'session_id',
    'db_data_col'   => 'session_value',
    'db_time_col'   => 'session_time',);

$session = new SessionProvider( new Chat() ,new Handler\PdoSessionHandler($pdo,$dbOptions));
$ws = new WsServer($session);
    $ws->disableVersion(0); // old, bad, protocol version

    // Make sure you're running this as root
    $server = IoServer::factory(new HttpServer($ws),8080);
    $server->run();




This is the Ratchet Websocket Server Part. 

So for now, I have a mysql table with the sessions based on cookies on Ratchet websocket. 


Now i want to add this to my php website, so they could share the same Cookie. 

As well commented by Chris on SessionProvider.php: * Your website must also use Symfony HttpFoundation Sessions to read your sites session data

Next weekend task is to include HttpFoundation on my web-page, so I could determine the same client on the site, and also, on the websocket. 
I am doing this to add security. Who is connecting to my websocket? 
And also to link the websocket tunnel with my user id. So I could determine which user has which websocket id. 

Until today, when the websocket client connects itself, it sends an id via the websocket. So I could Identify it. This is not secure, although it works. 


Leonardo Pucci

unread,
May 26, 2014, 9:26:10 AM5/26/14
to ratch...@googlegroups.com
This part is in my website, 



//This is if you are using Composer, your path will be diferent, change it!
require_once '../ratchet/vendor/autoload.php';

use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler;

$pdo = new PDO('mysql:host=localhost;dbname=DATABASE_NAME', 'MYSQL_USER', 'MYSQL_PASSWORD',array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$dbOptions = array(
    'db_table'      => 'TABLE_NAME',
    'db_id_col'     => 'session_id',
    'db_data_col'   => 'session_value',
    'db_time_col'   => 'session_time',);

$storage = new NativeSessionStorage(array(), new PdoSessionHandler($pdo,$dbOptions));
$session = new Session($storage);

//Here is the interesting part, i am getting the id and username from my mysql, and setting on the Symfony Session
$session->set('admin_id',$login->getUser_Id());
$session->set('username',$login->getUsername());

So, using $session->set,I set the variables that I want. Im my case I am using the Admin ID from my Mysql database to know who the admin is. 
Later, in my ratchet websocket code, I get the variable doing this:

 public function onOpen(ConnectionInterface $conn) {

 $Admin_Id = $conn->Session->get('admin_id');

 if(isset($Admin_Id) && !empty($Admin_Id)){
  
  $this->IdAdmin_WebSid[$Admin_Id] = $conn->resourceId;
   echo "Nova Conexao ADMIN!  ({$conn->resourceId})\n";

Everything working! 

Just a detail: 

I already have a Login system in my website. 

My code was using  session_start(); function to initiate php native sessions. 

If we are going to use Symphony, we cannot do session_start!. 

What to do then?

I have commented only this line:   // session_start();

And now the symphony login is instantiated BEFORE my login code. 

//Initializing Symphony Session
$session = new Session($storage);
//Now session is initialized and my code does not need to call session_start();

//Initializing my Login code without session_start()
$login = new Login();

That´s it! By the time that Symphony starts it, session is already started, then, my old code works like a charm!!


Any doubts,
Please Let me know

Leonardo Pucci

bris...@gmail.com

unread,
Jul 5, 2014, 9:38:11 AM7/5/14
to ratch...@googlegroups.com
Thanks!

Can you please help me on a memcached session storage using symfony 2 without the whole fymfony 2 framework?

I have posted a question here, but it is not visible yet, but the same question has been asked in symfony 2 forum:

http://forum.symfony-project.org/viewtopic.php?f=23&t=87770


thanks

Leonardo Pucci

unread,
Jul 5, 2014, 12:36:04 PM7/5/14
to ratch...@googlegroups.com, bris...@gmail.com
Try doing this:

Change this:
$session->getRequest()->getSession(); 

To this:

$session = new Session();
$session
->start();

=)

bris...@gmail.com

unread,
Jul 5, 2014, 4:03:53 PM7/5/14
to ratch...@googlegroups.com, bris...@gmail.com
Thanks, I change the following in home.php:

commented out:
$session =getRequest()->getSession(); 

and added:

$session = new Session();
$session->start();

It didn't work.

Any other suggestions?

bris...@gmail.com

unread,
Jul 5, 2014, 8:09:55 PM7/5/14
to ratch...@googlegroups.com, bris...@gmail.com
Since I cannot get normal php to work with sessions, I am trying to use it in Ratchet, here is my code:
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\App1;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler;
use Ratchet\Session\SessionProvider;
$pusher = new App1;
$memcached = new Memcached();
$memcached->addServer("127.0.0.1", 11211);
$session = new SessionProvider($pusher, new MemcachedSessionHandler($memcached));

$loop   = React\EventLoop\Factory::create();


$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind('tcp://127.0.0.1:5555');
$pull->on('message', array($pusher, 'onBlogEntry'));

$webSock = new React\Socket\Server($loop);
$webSock->listen(8080, '127.0.0.1');

$webServer = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer(
            new Ratchet\Wamp\WampServer(
                $pusher
            ),
        )
    ),
    $webSock
);
echo "Server is running\n";
$loop->run();


when I run it , I get:

PHP Warning:  Module 'memcached' already loaded in Unknown on line 0
PHP Catchable fatal error:  Argument 1 passed to Ratchet\Session\SessionProvider::__construct() must implement interface Ratchet\MessageComponentInterface, instance of App\App1 given, called in /home/tester/bin/MyServer.php on line 9 and defined in /home/tester/php/vendor/cboden/ratchet/src/Ratchet/Session/SessionProvider.php on line 47

What went wrong?

bris...@gmail.com

unread,
Jul 6, 2014, 7:41:00 AM7/6/14
to ratch...@googlegroups.com, bris...@gmail.com
OK, got the session in Ratchet working, the correct way to wrap it is

$webServer = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer(
            new SessionProvider(
                new Ratchet\Wamp\WampServer(
                    $pusher
                ),
                new MemcachedSessionHandler($memcached)
            )
        )
    ),
    $webSock
);

Now still need to find out why symfony 2 session is not working in my php

Leonardo Pucci

unread,
Jul 17, 2014, 12:33:53 PM7/17/14
to ratch...@googlegroups.com, bris...@gmail.com
Hello, 

I am enumerating some details here that you have to check put sympnhony to work:

Symfony sessions are incompatible with php.ini directive session.auto_start = 1 
This directive should be turned off in php.ini, in the webserver directives or in .htaccess.

Second mod:

COmment session_start() call. 
// session_start();
And initialize the simfony:
//Initializing Symphony Session
$session = new Session($storage);


Leonardo Pucci

unread,
Jul 28, 2014, 2:42:34 PM7/28/14
to ratch...@googlegroups.com, bris...@gmail.com
Another thing:

Cookie domain. 

Example: my socket runs on 

and the site is at www.site.com.br

so the cookie domain have to be set to all! So you have to set this on php.ini
session.cookie_domain = ".site.com.br"

javie...@gmail.com

unread,
Dec 22, 2014, 12:30:26 PM12/22/14
to ratch...@googlegroups.com
 
Hi !

Do I need then create session first from my site before use Ratchet server SessionProvider?

Thanks 
Message has been deleted

khawla gammoudi

unread,
Jun 17, 2015, 4:46:22 AM6/17/15
to ratch...@googlegroups.com
Hello,

I am new with websocket and i need some help please.
My boss at work propose to me to use this technology in order to send the data from the database to web page just if there is a new data enter in the database that is mean something like refresh but just in case new data enter it by the client.
Some help please ! i am blocked here really :( ( (((

Thank you very much 

Leonardo Pucci

unread,
Jun 17, 2015, 10:44:03 AM6/17/15
to ratch...@googlegroups.com

See the example in socketo.me/docs/push

--

---
You received this message because you are subscribed to a topic in the Google Groups "Ratchet" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/ratchet-php/rTOspZU7IZE/unsubscribe.
To unsubscribe from this group and all its topics, send an email to ratchet-php...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

khawla gammoudi

unread,
Jun 18, 2015, 3:39:40 AM6/18/15
to ratch...@googlegroups.com
Okay thank you for your help but i already tied it with this example but i had problem with 

ZMQ and wamp !!!!

Could you help me more please?

Sincerely yours,
Khaoula
--
KHAOULA GAMMOUDI
​Intern at medDV GmbH in the IT Development department. Polheim
, Germany.

Software developer Engineer graduated from the Private High School of Gabes.


Leonardo Pucci

unread,
Jun 18, 2015, 7:01:53 AM6/18/15
to ratch...@googlegroups.com

Post the errors/problems that you have trying the example.

We will be glad to help!

khawla gammoudi

unread,
Jun 18, 2015, 7:21:39 AM6/18/15
to ratch...@googlegroups.com
I have problems:
The first one was with wamp and ZMQ installation and configuration
The second one that this example woks with Node.js and i work just with xamp and notepad++ html&php&js

2015-06-18 13:01 GMT+02:00 Leonardo Pucci <leop...@gmail.com>:
Boxbe This message is eligible for Automatic Cleanup! (leop...@gmail.com) Add cleanup rule | More info

Post the errors/problems that you have trying the example.

We will be glad to help!

Em 18/06/2015 04:39, "khawla gammoudi" <khawlag...@gmail.com> escreveu:
Reply all
Reply to author
Forward
0 new messages