I'm trying to figure a way where my clients can ping my server via php, and then retrieve the results into format like this "15 MS".
I ended up finding a way where servers can ping servers. However I want to be able to have the remote user somehow ping the server, or maybe have the server ping the client possibly?
function track($host, $port, $timeout) {
$firstTime = microtime(true);
$sock = fSockOpen($host, $port, $errno, $errstr, $timeout);
if (!$sock) {
echo "<b>Offline</b>";
}
$secondTime = microtime(true);
$ping = round((($secondTime - $firstTime) * 1000), 0);
echo $ping." ms";
}
track($_SERVER["REMOTE_ADDR"], 80, 10);
I tried this function, where I'd get the server to ping the client to see the response time between the client/server.
fsockopen() [function.fsockopen]: unable to connect to XXXXXXXXXXX:80
I'm trying to figure a way where my clients can ping my server via php
Why? What's the value in knowing this information? Although I noted that Emil's answer didn't address the question, it might address the problem - the time it takes for an ICMP packet to go to a server and come back will be different from the time taken to complete a TCP handshake on port 80 across the internet (they should be roughly the same on a LAN provided the webserver is not saturated).
If you want to get good information about RTT times, then a better solution would be to use a network monitoring tool / software. PastMon is an obvious candidate.
If you really must send a ping from the client, then you'd need to do this using a java applet / flash / activeX (assuming that these have the low-level TCP stack access required to carry out a ping).
C.
What makes you think clients are going to reliably respond to ICMP echo requests?
A better solution would be to write a client-side Java applet (or JavaScript?) to ping your server.
Remember, security restrictions will limit both languages to only communicate back to their origin server. You won't be able to allow your users to ping a server besides your own... but that doesn't appear to be an issue in your case.
You have to do this in JavaScript. The client cannot run PHP at all, and your attempt to ping the client will not work when their firewall blocks requests from the outside (which is often the case).
Build a "ping" function in JS which fetches a page a few times by AJAX. This example is built upon the jQuery framework:
Web page/JS
<script src="jquery-1.4.2.min.js"></script>
<script>
var global_runs = 0;
function ping(data) {
var op = "";
if(global_runs == 0) {
op = "start";
}else if(global_runs == 3){
op = "end";
}else if(global_runs > 3) {
return;
}
global_runs++;
$.post("ping.php", {op: op}, ping);
if(data != null) {
$("#time").text(data + " MS");
}
}
$(document).ready(function(){
//Start pinging
ping();
});
</script>
<p id="time">Time will be here</p>
ping.php
<?php
session_start();
if($_POST['op'] == 'start' || !isset($_SESSION['start'])) {
$_SESSION['start'] = microtime(true);
$_SESSION['runs'] = 0;
}else{
$_SESSION['runs']++;
$now = microtime(true);
$time = $now - $_SESSION['start'];
echo ($time / $_SESSION['runs']) * 1000; //milliseconds
}
?>
I don't really make use of the end op here, but it can be used to let the server now that this is the last ping request. Note that this code trusts the client, which means you may need some extra work on the security on the serverside (maybe take away the whole notion of "ops" from the serverside and ust send the pings?). Also, you probably want different counters for each page, maybe identified by some token that you return in the first request.
Also note that this is depending on HTTP and CPU latency as well, not just the network, but I think it's as good as you can get it.
Related
I need help.
I tried every single script on every Stackoverflow question related to my problem that I found, but nothing worked.
I want to check (with PHP) if a given proxy (ip:port) is working or is dead. Simple.
The script will work with HTTP GET requests, like
http://example.com/check.php?ip=1.2.3.4&port=567
And the response will be "Working" or "Dead".
At the moment my script is this:
$ip = $_GET["ip"];
$port = $_GET["port"];
$waitTimeoutInSeconds = 1;
if($fp = fsockopen($ip,$port,$errCode,$errStr,$waitTimeoutInSeconds)){
echo "Working";
} else {
echo "Dead";
}
fclose($fp);
But every ip and port I send to this script the response is always "Working".
I tried every casual Ip and Port and the response is the same.
The example above will return "Working" too.
I think there is a problem.
Why?
:)
I am trying to receive data from a c# realtime application in my php server and then move a picture in the browser according to the data.
There is no problem in data send and receive, but the memory usage for chrome is getteng more and more when running the code.
If I close the socket inside the while loop, performance gets very low but mem usage gets normal.So this is about the open socket...
here is the php code :
<?php
//http://www.binarytides.com/udp-socket-programming-in-php/
//Create a UDP socket
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0)))
{
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
// Bind the source address
if( !socket_bind($sock, "0.0.0.0" , 41181) )
{
die("Could not bind socket : [$errorcode] $errormsg \n");
}
echo "Socket bind OK \n";
//Do some communication, this loop can handle multiple clients
while(1)
{
//echo "Waiting for data ... \n";
$r = socket_recvfrom($sock, $buf, 20, 0, $remote_ip, $remote_port);
?>
<script type="text/javascript">
var data = "<?php echo $buf ?>";
</script>
<?php
}
socket_close($sock);
?>
and here is the c# function (data sender):
public static void SendUDP(string hostNameOrAddress, int destinationPort, string data, int count)
{
//class member : Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
//socket is defined as class member and used here
for (int i = 0; i < count; i++)
{
socket.SendTo(buffer, endPoint);
}
}
Thanks ! :)
The technique you're using is called "long polling". It's a funny way to emulate bidirectional communication, especially with old browsers, but has its downsides.
The problem is that, with time, you are sending a huge amount of payload to the browser.
As you're continuously writing to the browser, the page size increases, and, with it, the DOM tree. All of this has to be stored in memory. I'd assume that when you send only a few of the script chunks, the performance is still ok. But thousands and ten thousands of them will of course eat up your memory.
Also, if you're using diagnostic tools, such as the Chrome Developer Tools or Firebug in Firefox, they store a lot of debugging information, which also consume a lot of memory. (Try disabling them.)
If you've written this code just for fun and experimenting, you shouldn't worry about the memory consumption; it's inherent to long polling.
But if you're trying to write a web application with a real bi-directional communication, you should use something like Web Sockets (and maybe a different language than PHP on the server side).
This is not a real answer to my question, but my experience may help someone.
I couldn't do this "long polling" with a PHP server, and it was the fault of PHP, not the browser.
I have developed a good application working this way using a Node.js server.
My C# app is used to process images from a camera. The real-time data resulting the image processing is sent over to the Node.js server and from the server to the browser .
Now I use the web technologies to develop a graphical user interface that was very hard to achieve in .Net, and it has many other benefits...
I have implemented the long polling successfully using normal Apache server, PHP, AJAX and Javascript. I don't use the Jquery to communicate with the server.
The problem is that the Apache server capabilities are limited, the server is not able to serve more than 5 browser tabs.
I wonder if there is any customization for the Apache or for the PHP to make them handle more concurrent connections? Or if there is any new/smart technique to do that? What are the maximum threads can be handled by a robust web server specialized in long polling?
I am not interested in the Web Sockets because of the browsers compatibility. I need something easy and robust into PHP. What Facebook are doing? I wonder how can they handle all the dynamic updates for million of users! What products/techniques they use?
A sample of my code:
srv_polling.php
<?php
function getResults(){..... return result;}
// recursive function inside the server
function hasResultChanged($old,$timeStart){
// to avoid server timeout (in seconds) in case no change for results
if(round(abs(time() - $timeStart) / 60*60,2) > 50)
return;
$new = getResults();
if($new != $old) // get back to browser
return true;
else{
$old = getResults();
sleep(2);
return $hasResultChanged($old,$timeStart);
}
}
$timeStart = time();
$old = $getResults();
sleep(2);
$hasResultChanged($old,$timeStart);
?>
// Javascript code to be executed at browser end
alert('Result has changed');
// Send AJAX request again to same page(srv_polling.php):
ajax.call({......})
Thank you for your hints! Greatly appreciated.
I am using this in my project
public function getLPollData($user, $handlerName) {
set_time_limit (600);
date_default_timezone_set('Europe/Berlin');
$counterEnd = (int)$_REQUEST["counterEnd"];
$counterStart = (int)$_REQUEST["counterStart"];
$this->expireNotifications($counterStart, $counterEnd);
$secCount = IDLE_WAIT;
do {
sleep(IDLE_TIME);
$updates = $this->fetchAllNotifications($counterEnd);
} while (!$updates && ($secCount--)>0);
if($updates){
}
header("HTTP/1.0 200");
return sprintf ('{"time" : "%s", "counter" : "%d", start : %d, data : %s}'
, date('d/m H:i:s'), $counterEnd,$counterStart,json_encode($updates));
}
Its combination of IDLE_WAIT & IDLE_TIME (10*3=~30 secs).
But i dont think your problem is on server side, if you are opening 5-6 connections from a browser, then remember each browser has limitation on how many active connections it can have to some particular domain, at a time. try diff browser or better diff machines, max two tabs in one browser.
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
I'm using fsockopen() to call a number of connections in a list to see the online status of various ip/host and ports ...
<?php
$socket = #fsockopen($row[2], $row[3], $errnum, $errstr, 1);
if ($errnum >= 1) { $status = 'offline'; } else { $status = 'online';}
fclose($socket);
if works, I'm not complaining about that, but I have approximately 15 ip/ports that i'm retrieving in a list (php for() command..). I was wondering if there is a better way to do this? This way is VERY slow!?! It is taking about 1-2 minutes for the server to come back with a response for all of them..
Update:
<?php
$socket = #fsockopen("lounge.local", "80", $errnum, $errstr, 30);
if ($errnum >= 1) { $status = 'offline'; } else { $status = 'online'; }
?>
It will display in a list: "ReadyNAS AFP readynas.local:548 online"
I don't know what more I can tell you? It just takes forever to load the collection of results...
From my own experience:
This code:
$sock=fsockopen('www.site.com', 80);
is slower compared to:
$sock=fsockopen(gethostbyname('www.site.com'), 80);
Tested in PHP 5.4. If doing many connections at the same time one could keep host resolution result and re-use it, to further reduce script time execution, for example:
function myfunc_getIP($host) {
if (isset($GLOBALS['my_cache'][$host])) {
return $GLOBALS['my_cache'][$host];
}
return $GLOBALS['my_cache'][$host]=gethostbyname($host);
}
$sock=fsockopen(myfunc_getIP('www.site.com'), 80);
If you plan to "ping" some URL, I would advise doing it with curl, why? you can use curl to send pings in parallel, have a look at this -> http://www.php.net/manual/en/function.curl-multi-init.php. In a previous project, it was supposed to feed Real Time Data to our server, we used to ping hosts to see if they are alive or not and Curl was the only option that helped us.
Its an advice, may not be a right solution for your problem.
The last parameter to fsockopen() is the timeout, set this to a low value to make the script complete faster, like this:
fsockopen('192.168.1.93', 80, $errNo, $errStr, 0.01)
Have you compared the results of fsockopen(servername) versus fsockopen(ip-address)? If the timeout parameter does not change a thing, the problem may be in your name server. If fsockopen with an IP address is faster, you'll have to fix your name server, or add the domains to /etc/hosts file.
I would recommend doing this a bit different.
Put this hosts in a table in a database something like:
++++++++++++++++++++++++++++++++++++
| host | port | status | timestamp |
++++++++++++++++++++++++++++++++++++
And move the status checking part in a cron script that you run it once every 5 minutes or how often you want.
This script will check the host:port and update status and timestamp for each record and in your page you will just do a db query and show the host, its status and when was last checked (something like: 1minute ago, etc...)
This way your page will load fast.
According to the php manual, there's a timeout parameter. Try setting it to a lower value.
Edit: To add to Daniel's answer, nmap might be the best tool to use. Set it up with a cron job to scan and update your records every X minutes. Something like
$ for ip in $(seq 6 8);
do
port_open=$(nmap -oG - -p 80 10.1.0.$ip|grep open|wc -l);
echo "10.1.0.$ip:$port_open";
done
10.1.0.6:1
10.1.0.7:1
10.1.0.8:0
I had an issue where fsockopen requests were slow, but wget was really snappy. In my case, it was happening because the hostname had both an ipv4 and ipv6 address, but ipv6 was down. So it took 20 or so seconds on each request for the ipv6 to time out.