Quick tip: Parsing ping results using PHP

This is just a quick tip while I’m moving into our new house (Nykøbing Falster, Denmark). I’ve been writing some security scripts for our router lately to notify me through Pushover when new devices appear on our network and let me block them by Mac with a single click. Don’t worry, we use WPA2-Personal on our WiFi, but we got lots of clients and so do our friends.

As you may have read earlier, have we switched to a 4G LTE connection entirely and run all our internet through this. It works great even through it only delivers 10/0.5 Mbit/sec at the new house, it’s the best we can get, until I’ve mounted a 4G antenna on the roof. I expect it to increase to about 30-50 Mbit/sec down and 10-20 Mbit/sec up when we’ve mounted this as it’s just pure luck (or lack thereof) that our house is right in a blind spot, as you can get full 4G LTE bars 400 meters up the road on a normal cellphone.

I’ve however decided that since I already got the Pi running with cronjobs to monitor our network, I might as well integrate my own Huawei API to get some statistics by the hour about bandwidth usage, ping statistics and internet speeds. Let’s start out by grabbing some ping statistics.

We all know how the linux command ping works. “Ping google.com” is probably the single most written command in internet history, maybe right after “cd” and “ls”. Let’s try it out with some params to automatically stop after a given number of pings. I like to ping 4 times so I have a nice average.

Which gives us the following output:

What horrible latency we got while I’m writing this article! Normally it’s around 30-50ms, but when using 4G it’s either all or nothing. Lucky enough it’s mostly “all”, but depending on cell usage and weather conditions, we might get as unlucky as the above.

You can see from the above that we get a nice and clean text output. But how do we actually use this text blob in PHP? I thought somebody had solved this before me, and maybe they have, but I couldn’t find any definitive (and working) answers on either Google or Stackoverflow.

So let’s just use “the magic of TV cooking” and jump to the answer as you are most likely searching for this yourself when reading this blog.

There you go! I thought about making a nice function or class, but this pure code is probably much easier to adopt to your own needs instead of trying to provide a complete solution up front for everybody. The most import thing you are looking for is most likely the two regexes that parse the actual results and how to do error handling.

This script grabs all the data from ping EXCEPT for “Request timed out” lines as I didn’t really care. I’m just going for the $pingStatistics variable!

Thanks for reading and I hope this post helped you out.