Related
I'm running a website which monitors some servers and there are more servers added daily.
Sadly my current solution is very slow (about 10 seconds loadtime for 31 servers). I'm using fsockopen which checks the IP and port. Because I parse a XML with the entries (host and port) I had to create a function and use this function in the parser so the visitors of the website can see the online or offline status of the server.
My current "checkserver" function looks like this:
function checkServer($ip, $port)
{
$fsockopen = #fsockopen($ip, $port, $errorNo, $errorStr, 1);
if (!$fsockopen)
return false;
else return true;
}
And in the parser the "if" rule for the server status looks like this:
if (checkServer((string)$server->host, (string)$server->port))
{
echo "SERVER ONLINE!";
}
else
{
echo "SERVER OFFLINE!";
}
Where $server is every single listed server in the XML <serverlist></serverlist> tag.
I already tried to change the timeout of fsockopen from 1 to 0.1 but some servers appear offline then and the loadtime is still at 8-10 seconds.
How could I speedup the loadtime? Could someone please help me with this?.. the project is very important for me. Thank you! I really appreciate every helpful answer!
First of all I would suggest caching. I am not sure how many users will open the page, but if you have multiple users per second opening the page you will have a lot of traffic to handle which on long term could create issues.
You have 2 solutions :
Using asynchronous events can allow you to do what you wish.T here are some libraries outhere doing this that can help you. I have used none sofar so I can't say which is best.
Using a library that cheats and uses exec & command lines : https://github.com/oliverde8/PHP-AsynchronousJobs
Using pthread library, this isn't a library coded in php, so it binaries you need to add to your http://pthreads.org/. You can add another library ontop to make the usage easier
Finally using javascript, so you open your page, then some ajax calls your php individually for each server & ask status.
I am trying to implement a realtime chat application using PHP . Is it possible to do it without using a persistent data storage like database or file . Basically what I need is a mediator written in PHP who
accepts messages from client browsers
Broadcasts the message to other clients
Forgets the message
You should check out Web Sockets of html5. It uses two way connection so you will not need any database or file. Any chat message comes to the server will directly sent to the other users browser without any Ajax call. But you need also to setup web socket server.
Web sockets are used in many real time applications as well. I am shortly planing to write full tutorial on that. I will notify you.
Just tried something I had never done before in response to this question. Seemed to work but I only tested it once. Instead of using a Socket I had an idea of using a shared Session variable. Basically I forced the Session_id to be the same value regardless of the user therefore they are all sharing the same data. From a quick test it seems to work. Here is what I did:
session_id('12345');
session_start();
$session_id = session_id();
$_SESSION['test'] = $_SESSION['test'] + 1;
echo "session: {$session_id} test: {$_SESSION['test']} <br />";
So my thought process was that you could simply store the chat info in a Session variable and force everyone regardless of who they are to use a shared session. Then you can simply use ajax to continually reload the current Session variable, and use ajax to edit the session variable when adding a message. Also you would probably want to set the Session to never expire or have a really long maxlifetime.
As I said I just played around with this for a few minutes to see if it would work.
You will want to use Sockets. This article will cover exactly what you want to do: http://devzone.zend.com/209/writing-socket-servers-in-php/
When I tried to solve the same problem, I went with Nginx's Push Module. I chose to go this way since I had to support older browsers (that usually won't support WebSockets) and had no confidence in setting up an appropriate solution like Socket.io behind a TCP proxy.
The workflow went like this:
The clients connect through long-polling to my /subscriber location, which is open to all.
The /publisher location only accepts connections from my own server
When a client subscribes and talks, it basically just asks a PHP script to handle whatever data is sent.
This script can do validation, authorization, and such, and then forwards (via curl) the message in a JSON format to the /publisher.
Nginx's Push Module handles sending the message back to the subscribers and the client establishes a new long-polling connection.
If I had to do this all over again, then I would definitely go the Socket.io route, as it has proper fallbacks to Comet-style long-polling and has great docs for both Client and Server scripts.
Hope this helps.
If you have a business need for PHP, then adding another language to the mix just means you then have two problems.
It is perfectly possible to run a permanent, constantly-running daemonised PHP IRCd server: I know, because I've done it, to make an online game which ran for years.
The IRC server part I used is a modified version of WaveIRCd:
http://sourceforge.net/projects/waveircd/
I daemonised it using code I made available here:
http://www.thudgame.com/node/254
That code might be overkill: I wrote it to be as rugged as I could, so it tries to daemonise using PHP's pcntl_fork(), then falls back to calling itself recursively in the background, then falls back to perl, and so on: it also handles the security restrictions of PHP's safe mode in case someone turns that on, and the security restrictions imposed by being called through cron.
You could probably strip it down to just a few lines: the bits with the comments "Daemon Rule..." - follow those rules, and you'll daemonize your process just fine.
In order to handle any unexpected daemon deaths, etc, I then ran that daemoniser every minute through cron, where it checked to see if the daemon was already running, and if so either quietly died, or if the daemon was nonresponsive, killed it and took its place.
Because of the whole distributed nature of IRC, it was nicely rugged, and gave me a multiplayer browser game with no downtime for a good few years until bit-rot ate the site a few months back. I should try to rewrite the front end in Flash and get it back up again someday, when I have time...
(I then ran another daemonizer for a PHP bot to manage the game itself, then had my game connect to it as a java applet, and talk to the bot to play the game, but that's irrelevant here).
Since WaveIRCd is no longer maintained, it's probably worth having a hunt around to find if anyone else has forked the project and is supporting it.
[2012 edit: that said, if you want your front end to be HTML5/Javascript, or if you want to connect through the same port that HTTP connects through, then your options are more limited than when using Flash or Java. In that case, take the advice of others, and use "WebSockets" (poor support in most current browsers) or the "Socket.io" project (which uses WebSockets, but falls back to Flash, or various other methods, depending what the browser has available).
The above is for situations where your host allows you to run a service on another port. In particular, many have explicit rules in their ToS against running an IRCd.]
[2019 edit: WebSockets are now widely supported, you should be fine using them. As a relevant case study, Slack is written in PHP (per https://slack.engineering/taking-php-seriously-cf7a60065329), and for some time supported the IRC protocol, though I believe that that has since been retired. As its main protocol, it uses an API based on JSON over WebSockets (https://api.slack.com/rtm). This all shows that a PHP IRCd can deliver enterprise-level performance and quality, even where the IRC protocol is translated to/from another one, which you'd expect to give poorer performance.]
You need to use some kind of storage as a buffer. It IS plausable not to use file or db (which also uses a file). You can try using php's shared memory functions, but I don't know any working solution so you'll have to do it from scratch.
Is it possible to do it without using a persistent data storage like
database or file?
It is possible but you shouldn't use. Database or file based doesn't slows down chat. It will be giving additional security to your chat application. You can make web based chat using ajax and sockets without persistent data.
You should see following posts:
Is database based chat room bad idea?
Will polling from a SQL DB instead of a file for chat application increase performance?
Using memcached as a database buffer for chat messages
persistent data in php question
https://stackoverflow.com/questions/6569754/how-can-i-develop-social-network-chat-without-using-a-database-for-storing-the-c
File vs database for storage efficiency in chat app
PHP is not a good fit for your requirements (in a normal setup like apache-php, fastcgi etc.), because the PHP script gets executed from top to bottom for every request and cannot maintain any state between the requests without the use of external services or databases/files (Except e.g. http://php.net/manual/de/book.apc.php, but it is not intended for implementing a chat and will not scale to multiple servers.)
You should definitely look at Node.js and especially the Node.js module Socket.IO (A Websocket library). It's incredibly easy to use and rocks. Socket.IO can also scale to multiple chat servers with an optional redis backend, which means it's easier to scale.
Trying to use $_SESSION with a static session id as communication channel is not a solution by the way, because PHP saves the session data into files.
One solution to achieving this is by writing a PHP socket server.
<?php
// Set time limit to indefinite execution
set_time_limit (0);
// Set the ip and port we will listen on
$address = '192.168.0.100';
$port = 9000;
$max_clients = 10;
// Array that will hold client information
$clients = Array();
// Create a TCP Stream socket
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
// Bind the socket to an address/port
socket_bind($sock, $address, $port) or die('Could not bind to address');
// Start listening for connections
socket_listen($sock);
// Loop continuously
while (true) {
// Setup clients listen socket for reading
$read[0] = $sock;
for ($i = 0; $i < $max_clients; $i++)
{
if ($client[$i]['sock'] != null)
$read[$i + 1] = $client[$i]['sock'] ;
}
// Set up a blocking call to socket_select()
$ready = socket_select($read,null,null,null);
/* if a new connection is being made add it to the client array */
if (in_array($sock, $read)) {
for ($i = 0; $i < $max_clients; $i++)
{
if ($client[$i]['sock'] == null) {
$client[$i]['sock'] = socket_accept($sock);
break;
}
elseif ($i == $max_clients - 1)
print ("too many clients")
}
if (--$ready <= 0)
continue;
} // end if in_array
// If a client is trying to write - handle it now
for ($i = 0; $i < $max_clients; $i++) // for each client
{
if (in_array($client[$i]['sock'] , $read))
{
$input = socket_read($client[$i]['sock'] , 1024);
if ($input == null) {
// Zero length string meaning disconnected
unset($client[$i]);
}
$n = trim($input);
if ($input == 'exit') {
// requested disconnect
socket_close($client[$i]['sock']);
} elseif ($input) {
// strip white spaces and write back to user
$output = ereg_replace("[ \t\n\r]","",$input).chr(0);
socket_write($client[$i]['sock'],$output);
}
} else {
// Close the socket
socket_close($client[$i]['sock']);
unset($client[$i]);
}
}
} // end while
// Close the master sockets
socket_close($sock);
?>
You would execute this by running it through command line and would always have to run for your PHP clients to connect to it. You could then write a PHP client that would connect to the socket.
<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: www.example.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
?>
You would have to use some type of ajax to call with jQuery posting the message to this PHP client.
http://devzone.zend.com/209/writing-socket-servers-in-php/
http://php.net/manual/en/function.fsockopen.php
Better use a node.js server for this. WebSockets aren't cross-browser nowadays (except socket.io for node.js that works perfect)
in short answer, you can't.
the current HTTP/HTML implementation doesn't support the pushstate so the algorithm of your chat app should follow :
A: sent message
B,C,D: do while a new message has been sent get this message.
so the receivers always have to make a new request and check if a new message has been sent. (AJAX Call or something similar )
so always there are a delay between the sent event and the receive event.
which means the data must be saved in something global, like db or file system.
take a look for :
http://today.java.net/article/2010/03/31/html5-server-push-technologies-part-1
You didn't say it had to all be written it PHP :)
Install RabbitMQ, and then use this chat implementation built on top of websockets and RabbitMQ.
Your PHP is pretty much just 'chat room chrome'. It's possible most of your site would fit within the 5 meg limit of offline HTML5 content, and you have a very flexible (and likely more robust than if you did it yourself) chat system.
It even has 20 messages of chat history if you leave the room.
https://github.com/videlalvaro/rabbitmq-chat
If You need to use just PHP, then You can store chat messages in session variables, session could be like object, storing a lot of information.
If You can use jQuery then You could just append paragraph to a div after message has been sent, but then if site is refreshed, messages will be gone.
Or combining, store messages in session and update that with jQuery and ajax.
Try looking into socket libraries like ZeroMQ they allow for instant transport of the message, and are quicker than TCP, and is realtime. Their infrastructure allows for instant data send between points A and B, without the data being stored anywhere first (although you can still choose to).
Here's a tutorial for a chat client in ZeroMQ
Well, I've been searching for material for this one, and failed to find anything. I am familiar with the IRC protocol, and I want to write IRC Services for my server (running on UnrealIRCD)
I prefer PHP, as I am most proficient there. Can anyone point me at some good tutorials or even explain here how to start? (I only need the basic protocol/syntax and server settings, I'll do the actual functions and abilities myself (hopefully :P)).
Thanks in advance.
A friend of mine me did this one already for InspIRCd. It never was finished, but the basics were working. We simply connected to the IRC server via a Socket-Connection (fsockopen in the first version, socket_create in the second one).
For communication we implemented an interface to InspIRCd with contained the specific lines as stated in the protocol. These methods could then be called by the core.
Reading uncompiled C source code of the Anope services got me pointed in the right direction, although it's a bit of a trial and error as to where to look inside it. I can't remember since it was quite a while ago when I tried my own PHP services, but if each client the services connects requires a PING/PONG reply to keep the connection alive, then won't PHP kinda fall down? The threading isn't that great, Linux only as far as I can remember.
EDIT: Good Lord, I didn't realize how old this question was. That being said, someone might use it so...answer below.
I've done this in PHP so I can tell you it can be done (source code not released).
That being said, I'll throw a basic core at you here:
$socket = socket_create(AF_INET, SOCK_STREAM, 6);
// Prevent fast reconnects if server down but try to connect every ten seconds.
while ( !socket_connect($socket,ADDRESS,PORT) ) {
sleep(10);
}
// set non blocking to avoid 'waiting' for data
socket_set_nonblock($socket);
// INTENTIONAL INFINITE LOOP
while(1) {
$read = array($socket);
// check if there's anything to read.
$num_changed_sockets = #socket_select($read, null, null, 0, 1);
if ( $num_changed_sockets > '0' ) {
// process the socket data here
processSocket(socket_read($socket,10000,PHP_NORMAL_READ));
}
}
Hope this helps you get started!
here is my problem: I have a script (let's call it comet.php) whic is requsted by an AJAX client script and wait for a change to happen like this:
while(no_changes){
usleep(100000);
//check for changes
}
I don't like this too much, it's not very scalable and it's (imho) "bad practice"
I would like to improve this behaviour with a semaphore(?) or anyway concurrent programming
technique. Can you please give me some tips on how to handle this? (I know, it's not a short answer, but a starting point would be enough.)
Edit: what about LibEvent?
You can solve this problem using ZeroMQ.
ZeroMQ is a library that provides supercharged sockets for plugging things (threads, processes and even separate machines) together.
I assume you're trying to push data from the server to the client. Well, a good way to do that is using the EventSource API (polyfills available).
client.js
Connects to stream.php through EventSource.
var stream = new EventSource('stream.php');
stream.addEventListener('debug', function (event) {
var data = JSON.parse(event.data);
console.log([event.type, data]);
});
stream.addEventListener('message', function (event) {
var data = JSON.parse(event.data);
console.log([event.type, data]);
});
router.php
This is a long-running process that listens for incoming messages and sends them out to anyone listening.
<?php
$context = new ZMQContext();
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind("tcp://*:5555");
$pub = $context->getSocket(ZMQ::SOCKET_PUB);
$pub->bind("tcp://*:5556");
while (true) {
$msg = $pull->recv();
echo "publishing received message $msg\n";
$pub->send($msg);
}
stream.php
Every user connecting to the site gets his own stream.php. This script is long-running and waits for any messages from the router. Once it gets a new message, it will output this message in EventSource format.
<?php
$context = new ZMQContext();
$sock = $context->getSocket(ZMQ::SOCKET_SUB);
$sock->setSockOpt(ZMQ::SOCKOPT_SUBSCRIBE, "");
$sock->connect("tcp://127.0.0.1:5556");
set_time_limit(0);
ini_set('memory_limit', '512M');
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
while (true) {
$msg = $sock->recv();
$event = json_decode($msg, true);
if (isset($event['type'])) {
echo "event: {$event['type']}\n";
}
$data = json_encode($event['data']);
echo "data: $data\n\n";
ob_flush();
flush();
}
To send messages to all users, just send them to the router. The router will then distribute that message to all listening streams. Here's an example:
<?php
$context = new ZMQContext();
$sock = $context->getSocket(ZMQ::SOCKET_PUSH);
$sock->connect("tcp://127.0.0.1:5555");
$msg = json_encode(array('type' => 'debug', 'data' => array('foo', 'bar', 'baz')));
$sock->send($msg);
$msg = json_encode(array('data' => array('foo', 'bar', 'baz')));
$sock->send($msg);
This should prove that you do not need node.js to do realtime programming. PHP can handle it just fine.
Apart from that, socket.io is a really nice way of doing this. And you could connect to socket.io to your PHP code via ZeroMQ easily.
See also
ZeroMQ
ZeroMQ PHP Bindings
ZeroMQ is the Answer - Ian Barber (Video)
socket.io
It really depends on what you are doing in your server side script. There are some situations in which your have no option but to do what you are doing above.
However, if you are doing something which involves a call to a function that will block until something happens, you can use this to avoid racing instead of the usleep() call (which is IMHO the part that would be considered "bad practice").
Say you were waiting for data from a file or some other kind of stream that blocks. You could do this:
while (($str = fgets($fp)) === FALSE) continue;
// Handle the event here
Really, PHP is the wrong language for doing stuff like this. But there are situations (I know because I have dealt with them myself) where PHP is the only option.
As much as I like PHP, I must say that PHP isn't the best choice for this task.
Node.js is much, much better for this kind of thing and it scales really good. It's also pretty simple to implement if you have JS knowledge.
Now, if you don't want to waste CPU cycles, you have to create a PHP script that will connect to a server of some sort on a certain port. The specified server should listen for connections on the chosen port and every X amount of time check for whatever you want to check (db entries for new posts for example) and then it dispatches the message to every connected client that the new entry is ready.
Now, it's not that difficult to implement this event queue architecture in PHP, but it'd take you literally 5 minutes to do this with Node.js and Socket.IO, without worrying whether it'll work in majority of browsers.
I agree with the consensus here that PHP isn't the best solution here. You really need to be looking at dedicated realtime technologies for the solution to this asynchronous problem of delivering data from your server to your clients. It sounds like you are trying to implement HTTP-Long Polling which isn't an easy thing to solve cross-browser. It's been tackled numerous times by developers of Comet products so I'd suggest you look at a Comet solution, or even better a WebSocket solution with fallback support for older browsers.
I'd suggest that you let PHP do the web application functionality that it's good at and choose a dedicated solution for your realtime, evented, asynchronous functionality.
You need a realtime library.
One example is Ratchet http://socketo.me/
The part that takes care of the pub sub is discussed at http://socketo.me/docs/wamp
The limitation here is that PHP also needs to be the one to initiate the mutable data.
In other words this wont magically let you subscribe to when MySQL is updated. But if you can edit the MySQL-setting code then you can add the publish part there.
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.
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.
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);
});
});
UPDATE: Aug 2014 The current socket.io v1.0 site has a PHP example:- https://github.com/rase-/socket.io-php-emitter
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);
});
});
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).
server.php (source code which will respond to all the client's request)
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!
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!
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.
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
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.
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.
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.
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 .