J Del J Del - 17 days ago 9
MySQL Question

Is there a way to modify node.js code via a PHP page?

So I'm using http://socket.io with node.js and developing a chat to learn more about node.js

I use node.js to communicate with MySQL when users open the page.

But for bandwidth reasons I can't keep using MySQL for everything so I store a few variables in there. For example I don't want the user signed in twice, so I would store the socket ID for all users in JSON. If the socket ID already exists for that user (in node.js), then I would disconnect the socket.

This works fine, but let's say I wanted to disconnect a user, how would I go about doing that with PHP?

One option I've considered is maybe I update a table in the database with the required changes and then node.js checks that table every 60 seconds and does what it needs to do, then updates the table after the changes are completed.

Is that the best option or should I try to accomplish this with PHP? Obviously PHP would be more immediate -- but that's not too much of a concern for me.

Answer

It's quite simple:

  1. Make sure your node.js code supports HTTP requests and not just sockets.

  2. Add a route to perform any actions. For instance you could handle /api/disconnect/:userId which would do whatever you need.

  3. In your PHP code, call the relevant URL using either file_get_contents or the cURL family of calls.

Of course, you want to make sure you have some decent security so that only your PHP script can call you webservices, otherwise you'd open the door to all sorts of attacks. In the short term, this could be done simply by only listening 127.0.0.1 and using that address to communicate.

Note that the title of your question does not actually match its text. You're not actually modifying the node.js code, you're just modifying the data it manipulates.