Yes, It’s + not VS.

This is an idea of mine to connect PHP and Node.JS for real-time systems.

Why Node.JS?

The reason why developers are preferring Node.JS over PHP is that PHP’s fewer resources for real-time communication technologies such as web sockets.

To do that, do we need to reprogram our website in Node.JS? No. Continue reading…

Prerequisites

  1. Way to make local HTTP Requests (cURL or anything)

Let’s make PHP and Node.JS Friends

  • When a user sends a message, you send an AJAX request to a PHP script (message.php) and updates the database adding the new message into it.
  • Now the problem occurs. We need to notify the user in the other end about this message, right?

How can we do this?

We can setup Node.JS for this.

Setting up Node.JS server

Is our node.js server a web sockets server? No. It should be both web sockets and HTTP server.

  1. Clients connect to the server via WebSockets.
  2. PHP scripts connect to the server via password protected HTTP Requests.

Protect HTTP requests with a password to avoid others accessing it.

Let’s Continue

“Hello, Node.JS I received an update, please send it to the users who are connected via web sockets. But, don’t send it to all. Here are the user IDs who need this notification to receive: 234,253,235, etc.”

Then, Node.JS sends updates to the relevant users.

Connecting client-side to Node.JS

Then, add a listener to the onmessage event and listen to the updates from Node.JS.

Conclusion

Edit: Finally I could write the tutorial on this concept at my blog: https://developer.hyvor.com/php/chat-app-with-php-nodejs

Founder of Hyvor

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store