PHP + Node.JS
This is an idea of mine to connect PHP and Node.JS for real-time systems.
Assume that you have a website running on Apache or NGNIX written in PHP, and you need to make your website real-time.
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…
- A computer running both PHP and Node.JS
- Way to make local HTTP Requests (cURL or anything)
Let’s make PHP and Node.JS Friends
Let’s think it is a chat app.
- 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
A web server normally runs on the port 80. So, we can choose a port like 8080 to run our node.js server.
Is our node.js server a web sockets server? No. It should be both web sockets and HTTP server.
- Clients connect to the server via WebSockets.
- PHP scripts connect to the server via password protected HTTP Requests.
Protect HTTP requests with a password to avoid others accessing it.
In the previous step, the user sent a message which was handled by
message.php . Now, we can add a code to send an HTTP request to port 8080, saying,
“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.
This is a demonstration of the idea of connecting PHP and Node.JS. I’ll try to post the code of this if I get time. You may think if this would work. Yes, It works. I use it in my website, Hyvor Talk.
Edit: Finally I could write the tutorial on this concept at my blog: https://developer.hyvor.com/php/chat-app-with-php-nodejs