153

Is it possible to use Sockets.io on the client side and communicate with a PHP based application on the server? Does PHP even support such a 'long-lived connection' way of writing code?

All the sample code I find for socket.io seems to be for node.js on the server side, so no help there.

Sinister Beard
  • 3,570
  • 12
  • 59
  • 95
Yuvi
  • 4,447
  • 8
  • 35
  • 42

12 Answers12

108

It may be a little late for this question to be answered, but here is what I found.

I don't want to debate on the fact that nodes does that better than php or not, this is not the point.

The solution is : I haven't found any implementation of socket.io for PHP.

But there are some ways to implement WebSockets. There is this jQuery plugin allowing you to use Websockets while gracefully degrading for non-supporting browsers. On the PHP side, there is this class which seems to be the most widely used for PHP WS servers.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
  • 1
    the phpwebsocket class is indeed the way to go if you want a php websocket server implementation. However this is not related to the question. The OP already has a WS server (socket.io) implemented and asked for ways to communicate with a php application. – kasper Taeymans Dec 27 '13 at 11:09
79

If you want to use socket.io together with php this may be your answer!

project website:

elephant.io

they are also on github:

https://github.com/wisembly/elephant.io

Elephant.io provides a socket.io client fully written in PHP that should be usable everywhere in your project.

It is a light and easy to use library that aims to bring some real-time functionality to a PHP application through socket.io and websockets for actions that could not be done in full javascript.

example from the project website (communicate with websocket server through php)

php server

use ElephantIO\Client as Elephant;

$elephant = new Elephant('http://localhost:8000', 'socket.io', 1, false, true, true);

$elephant->init();
$elephant->send(
    ElephantIOClient::TYPE_EVENT,
    null,
    null,
    json_encode(array('name' => 'foo', 'args' => 'bar'))
);
$elephant->close();

echo 'tryin to send `bar` to the event `foo`';

socket io server

var io = require('socket.io').listen(8000);

io.sockets.on('connection', function (socket) {
  console.log('user connected!');

  socket.on('foo', function (data) {
    console.log('here we are in action event and data is: ' + data);
  });
});
kasper Taeymans
  • 6,950
  • 5
  • 32
  • 51
  • 2
    I'll give you a +1 here, but it looks like this is still a little ways from being usable in a production environment. – Beachhouse Nov 24 '12 at 17:13
  • 21
    I've seen this one, but one thing confused me. Isn't the point here to have PHP implement a sockets.io server? and, instead, Elepant.io seems to be a PHP implementation of a sockets.io client for which you can connect to some other sockets.io server (meaning, elephant.io is not listening for connections from your sockets.io clients, connecting to them and servicing them)? – Pimp Trizkit Dec 23 '12 at 05:36
  • Just what I came looking for, pity that the persistent connection is in early stage of development. – slezadav May 10 '13 at 11:43
  • 8
    Hi all. Elephant.io aim is just to fire events from PHP to a socket.io server. Not to open a persistent connexion. But to be able to quickly connect and send events / messages. We use it in production and it works like a charm. – guillaumepotier Jun 13 '13 at 16:52
  • Hi! How did you used it in production? I mean, how can you send data to socket.io and know that it comes from your server and not other client? Is sending a secret password along with the data a good option? –  Mar 27 '14 at 15:39
  • 3
    this library is not maintained anymore and has some issues for us – Flion Jul 12 '16 at 13:19
  • Elephant is dead now. RIP – J4GD33P 51NGH Oct 09 '18 at 13:11
  • Here's a actively mantained fork: https://github.com/ElephantIO/elephant.io/tree/master – campsjos Jul 25 '23 at 18:41
24

If you really want to use PHP as your backend for socket.io ,here are what I found. Two socket.io php server side alternative.

https://github.com/walkor/phpsocket.io

https://github.com/RickySu/phpsocket.io

Exmaple codes for the first repository like this.

use PHPSocketIO\SocketIO;

// listen port 2021 for socket.io client
$io = new SocketIO(2021);
$io->on('connection', function($socket)use($io){
  $socket->on('chat message', function($msg)use($io){
    $io->emit('chat message', $msg);
  });
});
walkor
  • 276
  • 2
  • 4
23

UPDATE: Aug 2014 The current socket.io v1.0 site has a PHP example:- https://github.com/rase-/socket.io-php-emitter

Alvin K.
  • 4,329
  • 20
  • 25
15

I know the struggle man! But I recently had it pretty much working with Workerman. If you have not stumbled upon this php framework then you better check this out!

Well, Workerman is an asynchronous event driven PHP framework for easily building fast, scalable network applications. (I just copied and pasted that from their website hahahah http://www.workerman.net/en/)

The easy way to explain this is that when it comes web socket programming all you really need to have is to have 2 files in your server or local server (wherever you are working at).

  1. server.php (source code which will respond to all the client's request)

  2. client.php/client.html (source code which will do the requesting stuffs)

So basically, you right the code first on you server.php and start the server. Normally, as I am using windows which adds more of the struggle, I run the server through this command --> php server.php start

Well if you are using xampp. Here's one way to do it. Go to wherever you want to put your files. In our case, we're going to the put the files in

C:/xampp/htdocs/websocket/server.php

C:/xampp/htdocs/websocket/client.php or client.html

Assuming that you already have those files in your local server. Open your Git Bash or Command Line or Terminal or whichever you are using and download the php libraries here.

https://github.com/walkor/Workerman

https://github.com/walkor/phpsocket.io

I usually download it via composer and just autoload those files in my php scripts.

And also check this one. This is really important! You need this javascript libary in order for you client.php or client.html to communicate with the server.php when you run it.

https://github.com/walkor/phpsocket.io/tree/master/examples/chat/public/socket.io-client

I just copy and pasted that socket.io-client folder on the same level as my server.php and my client.php

Here is the server.php sourcecode

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

use Workerman\Worker;
use PHPSocketIO\SocketIO;

// listen port 2021 for socket.io client
$io = new SocketIO(2021);
$io->on('connection', function($socket)use($io){
    $socket->on('send message', function($msg)use($io){
        $io->emit('new message', $msg);
    });
});

Worker::runAll();

And here is the client.php or client.html sourcecode

<!DOCTYPE html>
<html>
    <head>
        <title>Chat</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">        
    </head>
    <body>
        <div id="chat-messages" style="overflow-y: scroll; height: 100px; "></div>        
        <input type="text" class="message">
    </body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    
    <script src="socket.io-client/socket.io.js"></script>  
    <script>
            var socket = io.connect("ws://127.0.0.1:2021");

            $('.message').on('change', function(){
                socket.emit('send message', $(this).val());
                $(this).val('');
            });

            socket.on('new message', function(data){
                $('#chat-messages').append('<p>' + data +'</p>');
            });
    </script>
</html>

Once again, open your command line or git bash or terminal where you put your server.php file. So in our case, that is C:/xampp/htdocs/websocket/ and typed in php server.php start and press enter.

Then go to you browser and type http://localhost/websocket/client.php to visit your site. Then just type anything to that textbox and you will see a basic php websocket on the go!

You just need to remember. In web socket programming, it just needs a server and a client. Run the server code first and the open the client code. And there you have it! Hope this helps!

mr_nobody
  • 356
  • 2
  • 4
7

For 'long-lived connection' you mentioned, you can use Ratchet for PHP. It's a library built based on Stream Socket functions that PHP has supported since PHP 5.

For client side, you need to use WebSocket that HTML5 supported instead of Socket.io (since you know, socket.io only works with node.js).

In case you still want to use Socket.io, you can try this way: - find & get socket.io.js for client to use - work with Ratchet to simulate the way socket.io does on server

Hope this helps!

Chung Xa
  • 111
  • 1
  • 4
  • So how do you simulate how socket.io works with Ratchet? Because if you just establish a normal connection with Ratchet, it is not recognized by a socket-io client due to missing metadata. – Sarah Multitasker May 19 '21 at 06:59
6

Erm, why would you want to? Leave PHP on the backend and NodeJS/Sockets to do its non-blocking thing.

Here is something to get you started: http://groups.google.com/group/socket_io/browse_thread/thread/74a76896d2b72ccc

Personally I have express running with an endpoint that is listening expressly for interaction from PHP.

For example, if I have sent a user an email, I want socket.io to display a real-time notification to the user.

Want interaction from socket.io to php, well you can just do something like this:

var http = require('http'),
            host = WWW_HOST,
            clen = 'userid=' + userid,
            site = http.createClient(80, host),
            request = site.request("POST", "/modules/nodeim/includes/signonuser.inc.php",  
                {'host':host,'Content-Length':clen.length,'Content-Type':'application/x-www-form-urlencoded'});                     

request.write('userid=' + userid);      
request.end();  

Seriously, PHP is great for doing server side stuff and let it be with the connections it has no place in this domain now. Why do anything long-polling when you have websockets or flashsockets.

PaulM
  • 3,281
  • 3
  • 28
  • 38
  • 38
    Because some of us are only able to get a cheap host that will only let you use php and mysql. – Lanbo Oct 24 '11 at 11:55
  • there are some cheap vps providers that allow you to run anything for $5 USD a month. You really have no excuse. – PaulM Oct 24 '11 at 13:03
  • 1
    Then please point me to these, I've been looking for some months. – Lanbo Oct 24 '11 at 17:05
  • Check out: http://www.lowendbox.com/ then http://www.lowendbox.com/blog/weserveit-5-euro-128mb-xen-vps-in-netherlands/ http://webkeepers.com/ http://www.cheapvps.co.uk/ http://www.vps247.com/ - I'm sure you'll find lots of very cheap stuff here. Just do a google search for cheap vps, that's what I did. – PaulM Oct 24 '11 at 17:19
  • 38
    Because some of us have to work with existing frameworks that depend on PHP. For example we develop and sell a PHP script, but would like to improve the IM by using websockets, we dont want to write all the fallbacks that socket.io already implemented but we cannot require NodeJS from our clients. – Purefan Oct 31 '11 at 09:09
  • Don't forget to define the Encoding: response.setEncoding('utf8'); – Ryan Schumacher Dec 30 '11 at 04:18
  • 4
    @PaulM: I tried few <$10 VPS providers, and all of those really suck. Each were *very* slow, when something is broken, support is horrible etc. On the other hand, in Finland it's not rare to get decent quality web hosting (but with php/mysql/static files only) with adsl subscription, without paying any extra. So no, being able to buy crappy VPS for $5 is definitely not a solution. – Olli Apr 01 '12 at 12:51
  • 4
    For <$10 VPS providers, the only decent one I've found so far is digitalocean.com. But that one is pretty good. – Aeolun Jan 05 '13 at 05:06
  • 4
    I don't agree. I think an answer like this is very relevant. Someone telling you "you're using it wrong" could be worth a lot more than someone helping you to use it wrong. – Rijk Jun 07 '13 at 14:25
  • @PaulM That's not cheap. I'm paying U$S 0.80/month/site for a good and fast PHP server, with support in my language (Spanish), easy for payment (any drug store in cash, don't need credit card or any other complications). That's not a solution, and it's not what OP asked. – ESL Mar 17 '16 at 15:18
  • I come from the future: AWS Amazon offers t2.nano instances which are really cheap, fast, and you can hire them on demand (pay per second) or reserved (with discounts up to 3 year). If you also need a domain name, you can order your domain at Route53 and use AWS certificates for your HTTPS. – bvdb Jan 15 '20 at 10:18
4

If you really want to use PHP as your backend for WebSockets, these links can get you on your way:

https://github.com/lemmingzshadow/php-websocket

http://www.htmlgoodies.com/html5/other/create-a-bi-directional-connection-to-a-php-server-using-html5-websockets.html#fbid=QqpDVi8FqD9

Chris Hanson
  • 2,043
  • 3
  • 16
  • 26
  • 1
    Do these allow you to use socket.io (with all its supported transports and browsers). Or do you have to use the client that comes with php-websocket? – Darren Cook Feb 14 '13 at 09:06
4

How about this ? PHPSocketio ?? It is a socket.io php server side alternative. The event loop is based on pecl event extension. Though haven't tried it myself till now.

Sankalp Singha
  • 4,461
  • 5
  • 39
  • 58
2

I haven't tried it yet, but you should be able to do this with ReactPHP and this socket component. Looks just like Node, but in PHP.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
1

I was looking for a really simple way to get PHP to send a socket.io message to clients.

This doesn't require any additional PHP libraries - it just uses sockets.

Instead of trying to connect to the websocket interface like so many other solutions, just connect to the node.js server and use .on('data') to receive the message.

Then, socket.io can forward it along to clients.

Detect a connection from your PHP server in Node.js like this:

//You might have something like this - just included to show object setup
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);

server.on("connection", function(s) {
    //If connection is from our server (localhost)
    if(s.remoteAddress == "::ffff:127.0.0.1") {
        s.on('data', function(buf) {
            var js = JSON.parse(buf);
            io.emit(js.msg,js.data); //Send the msg to socket.io clients
        });
    }
});

Here's the incredibly simple php code - I wrapped it in a function - you may come up with something better.

Note that 8080 is the port to my Node.js server - you may want to change.

function sio_message($message, $data) {
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    $result = socket_connect($socket, '127.0.0.1', 8080);
    if(!$result) {
        die('cannot connect '.socket_strerror(socket_last_error()).PHP_EOL);
    }
    $bytes = socket_write($socket, json_encode(Array("msg" => $message, "data" => $data)));
    socket_close($socket);
}

You can use it like this:

sio_message("chat message","Hello from PHP!");

You can also send arrays which are converted to json and passed along to clients.

sio_message("DataUpdate",Array("Data1" => "something", "Data2" => "something else"));

This is a useful way to "trust" that your clients are getting legitimate messages from the server.

You can also have PHP pass along database updates without having hundreds of clients query the database.

ethry
  • 731
  • 6
  • 17
user1274820
  • 7,786
  • 3
  • 37
  • 74
  • 1
    Nice idea, I was looking for a way to skip redis (if that's a good idea)! There's a typo in the first code, a semicolon after `s.remoteAddress;`. However, I'm not getting it to work. I get the connection in node, it detects the connection, the remoteaddress is correct, but `s.on('data')` never happens, but nothing happens. I tried `s.on('msg')` too. I'm using your exact PHP code. I'm using https, for the node server, but that shouldn't matter? – Niclas Dec 08 '18 at 11:46
  • @Niclas hey sorry about the typo - can't believe that was there all along. Is your node server running on port `8080`? If not, you need to change the port. If so, check the `Remote Address` that's being returned - make sure it's the loopback/local address - it may be different with your server setup. For testing, you can remove the line `if(s.remoteAddress == "::ffff:127.0.0.1")` – user1274820 Dec 08 '18 at 20:20
  • Thanks for the quick reply! I did successfully console.log all the way, even the remoteaddress was right, it just doesn’t enter the s.on(’data’) section. Is there a way to test what message was sent? Please re-read my comment to see if I missed something. I might start this as a new question to post the code but it’s almost exactly like yours. – Niclas Dec 09 '18 at 03:10
  • I started this as a new question to make it easier to discuss in detail: https://stackoverflow.com/questions/53689391/send-message-from-php-directly-to-node-using-socket-only-without-redis-etc – Niclas Dec 09 '18 at 04:32
0

Look in this libraryes for php http://phptrends.com/category/70. Or use native from php http://www.php.net/manual/en/book.sockets.php .

Knase
  • 1,224
  • 14
  • 23