I’m thinking about giving my users a nice little extra feature: I want to add push notifications. This is the use case:
People have a guestbook at their profile page. When someone posts a message in a user’s guestbook, that user will receive a push notification (if he’s online ofcourse). If he’s not online, the next time he comes online, we’ll just pull the notifications from the DB.
I was thinking about doing this with Socket.IO running on a Node.JS server. My current application is built with PHP (so the posting etc. is handled by PHP).
All online users will connect using Socket.IO to listen for their own notifications. Their socket will be saved in an array or hash on the server.
This is the flow I have in mind:
- UserA posts a message in guestbook of UserB
- Make Socket.IO emit a notification to UserB (if online, so known by Socket.IO)
- Save the message in DB
The issue here is the ‘make Socket.IO emit a notification‘-part. I would need a way to do this from PHP, because I want the server to emit this notification and not the user that is posting the message. Why you ask? I want to prevent malicious users from creating fake notifications. So in pseudocode the PHP application would look like this:
// do some validations here ... // This is the message that was posted $message = array( 'from' => 'UserA', 'to' => 'UserB', 'msg' => 'Hello you' ); // Send a notification to the user by emitting an event socketio_emit('notification', json_encode($message)); save_in_db($message);
What are your thoughts about this? Are there better ways to implement this seemingly small feature? And also, how would I do the
socketio_emit() in PHP, in other words: how do I communicate with a Socket.IO server using PHP?
Thanks a lot!
I solved this by using Express.js and CURL to post new notifications. The Node.js server listens to a specific URL, e.g. /new_notification. Doing a POST request from my webserver with CURL to that URL, I can add new notifications and handle them with Socket.IO (all in the same Node.js application).