简体   繁体   中英

How do i pass a PHP variable or session through nodeJS to socket.io on connection

I'm currently building a chat for my website which is built in PHP with MongoDB.

When the user Logs in i create Session variables for the user but can't seem to find a way to pass that variable through nodejs to socket.io.

I use this in the chat html page

var socket = io('http://localhost:3000', { query: *I need my php information here* });

Ajax defeats the purpose and is too slow.

Notes: i know i can pass with ajax on message but i'd prefer to pass on connection.

Im using this code in my server.js which makes it impossible for it to be .php file

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

You could pass your PHP information in a global Javascript variable. Something like

<script>var phpInfo = "<%= $yourInfo =>"</script>

( here the <%= stand for <?php echo "" ?> )
You can then use this variable into your connection

var socket = io('http://localhost:3000', { query: phpInfo });

This is not optimal but it works, Another way you could do that is retreive your info at some point (either then the user connect or when you load the main page) and save this into the HTML5 localStorage using window.localStorage.setItem('phpInfo', phpinfo) and then access this data using window.localStorage.getItem('phpInfo')
This is a more elegent way to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM