Subscribe to PHP Freaks RSS

Sockets with PHP and Node

syndicated from on July 21, 2017

I was looking to implement real time notifications system via sockets without having to use any third party services such as Pusher, etc. I just wanted to be able to send notifications from PHP side to the client and instantly show them on the web application similar to Facebook notifications.

First I came across ratchet library, it worked great but problem emerged when setting it up on secure connection (https) on my host (siteground), tried apache proxy module and everything else told on the internet but to no avail (it seems siteground has problem with ratchet on https) so in the end I had to drop ratchet.

Then I thought of using with Node+PHP and with my research I came across library (though it isn't updated recently) and this one worked wonderfully well both on non-secure and secure protocols allowing us to send and receive messages from PHP with node-based server.

Here are the steps that I followed to get my notification system working.


For your PHP application, install via composer:

composer require wisembly/

Install Node Dependencies

Create a directory in your project root and under it create a file named package.json with these contents:

    "name": "elephantIO_example_emitter",
    "version": "3.0.0",
    "main": "server.js",

"scripts": { "start": "supervisor --debug server.js" },

"dependencies": { "": "~1", "winston": "*" } }

On newly created directory run command npm install --save. This will install and logger library.

In same newly created directory, create a file server.js with these contents:

var server     = require('http').createServer(),
    io         = require('')(server),
    logger     = require('winston'),
    port       = 1337;

// Logger config logger.remove(logger.transports.Console); logger.add(logger.transports.Console, { colorize: true, timestamp: true });'SocketIO > listening on port ' + port);

io.on('connection', function (socket){ var nb = 0;'SocketIO > Connected socket ' +;

socket.on('broadcast', function (message) { ++nb;'ElephantIO broadcast > ' + JSON.stringify(message));

// send to all connected clients io.sockets.emit("broadcast", message); });

socket.on('disconnect', function () {'SocketIO : Received ' + nb + ' messages');'SocketIO > Disconnected socket ' +; }); });


Run server.js file through node by typing node server.js, you should see message that server has started on specified port.

Client Side

Put following javascript code in your application's page/footer:

<script src='//'></script>

<script> var socket = io.connect('//');

socket.on('connect', function () { console.log('connected');

socket.on('broadcast', function (data) { //console.log(data); //socket.emit("broadcast", data); alert(data.text); });

socket.on('disconnect', function () { console.log('disconnected'); }); }); </script>

Sending Notification from PHP

Here is how you can send a message to all connected clients:

require __DIR__ . '/vendor/autoload.php';

use ElephantIO\Client; use ElephantIO\Engine\SocketIO\Version1X;

$client = new Client(new Version1X('//'));

$client->initialize(); // send message to connected clients $client->emit('broadcast', ['type' => 'notification', 'text' => 'Hello There!']); $client->close();

and that's all there is to it.

Installing and Running Node on Production Site

I was on CentOSv6 and I installed node by following this guide. Then I created simple php file that will be run by cron so that node server is automatically started/restarted if it is not running:

$nodePath = 'your node binary path here';
$filePath = 'your server.js file path';
shell_exec($nodePath . ' ' . $filePath);

and then specify that file in cron to run at your specified time intervals.

Important Notes

  • I was having bit

Truncated by Planet PHP, read more at the original (another 868 bytes)