[php] Pinging an IP address using PHP and echoing the result

I have the following function that I doesn't work so far. I would like to ping an IP address and then to echo whether the IP is alive or not.

function pingAddress($ip){
    $pingresult = shell_exec("start /b ping $ip -n 1");
    $dead = "Request timed out.";
    $deadoralive = strpos($dead, $pingresult);

    if ($deadoralive == false){
        echo "The IP address, $ip, is dead";
    } else {
        echo "The IP address, $ip, is alive";
    }

}

When I call this function using the example:

pingAddress("127.0.0.1")

The echo result is always 'dead' - no matter what.

Could someone please help me where I'm going wrong? And/OR is there a better method of doing this with the same result?

Many thanks.

Update: Have amended code to include the double quotes but still getting the same (incorrect) results.

This question is related to php ping shell-exec

The answer is


This also did not work for me in Wordpress. I also tried -t and -n and other ways, but did not work. I used,

function pingAddress($ip) {
    $pingresult = exec("/bin/ping -c2 -w2 $ip", $outcome, $status);  
    if ($status==0) {
    $status = "alive";
    } else {
    $status = "dead";
    }
    $message .= '<div id="dialog-block-left">';
    $message .= '<div id="ip-status">The IP address, '.$ip.', is  '.$status.'</div><div style="clear:both"></div>';    
    return $message;
}
// Some IP Address
pingAddress("192.168.1.1"); 

This worked perfectly for me, finally. I referred this from http://www.phpscriptsdaily.com/php/php-ping/ Hope this will help

Well I want to modify this as it is working fine on my localhost but not on my live server For live server, I got another thing which now works for both local as well as live.

$fp = fSockOpen($ip,80,$errno,$errstr,1);
if($fp) { $status=0; fclose($fp); } else { $status=1; }

Then I show the Server is up for 0 and down for 1.

This works perfectly for me. I got this from Ping site and return result in PHP Thanks @karim79


This works fine with hostname, reverse IP (for internal networks) and IP.

function pingAddress($ip) {
    $ping = exec("ping -n 2 $ip", $output, $status);
    if (strpos($output[2], 'unreachable') !== FALSE) {
        return '<span style="color:#f00;">OFFLINE</span>';
    } else {
        return '<span style="color:green;">ONLINE</span>';
    }
}

echo pingAddress($ip);

Do check the man pages of your ping command before trying some of these examples out (always good practice anyway). For Ubuntu 16 (for example) the accepted answer doesn't work as the -n 3 fails (this isn't the count of packets anymore, -n denotes not converting the IP address to a hostname).

Following the request of the OP, a potential alternative function would be as follows:

function checkPing($ip){
    $ping = trim(`which ping`);
    $ll = exec($ping . '-n -c2 ' . $ip, $output, $retVar);
    if($retVar == 0){
        echo "The IP address, $ip, is alive";
        return true;
    } else {
        echo "The IP address, $ip, is dead";
        return false;
    }
}

this works fine for me..

$host="127.0.0.1";
$output=shell_exec('ping -n 1 '.$host);

echo "<pre>$output</pre>"; //for viewing the ping result, if not need it just remove it

if (strpos($output, 'out') !== false) {
    echo "Dead";
}
    elseif(strpos($output, 'expired') !== false)
{
    echo "Network Error";
}
    elseif(strpos($output, 'data') !== false)
{
    echo "Alive";
}
else
{
    echo "Unknown Error";
}

For Windows Use this class

$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency !== false) {
 print 'Latency is ' . $latency . ' ms';
}
else {
print 'Host could not be reached.';
}

https://github.com/geerlingguy/Ping


I have developed the algorithm to work with heterogeneous OS, both Windows and Linux.

Implement the following class:

<?php

    class CheckDevice {

        public function myOS(){
            if (strtoupper(substr(PHP_OS, 0, 3)) === (chr(87).chr(73).chr(78)))
                return true;

            return false;
        }

        public function ping($ip_addr){
            if ($this->myOS()){
                if (!exec("ping -n 1 -w 1 ".$ip_addr." 2>NUL > NUL && (echo 0) || (echo 1)"))
                    return true;
            } else {
                if (!exec("ping -q -c1 ".$ip_addr." >/dev/null 2>&1 ; echo $?"))
                    return true;
            }

            return false;
        }
    }

    $ip_addr = "151.101.193.69"; #DNS: www.stackoverflow.com

    if ((new CheckDevice())->ping($ip_addr))
        echo "The device exists";
    else 
        echo "The device is not connected";

i just wrote a very fast solution by combining all knowledge gain above

    function pinger($address){
        if(strtolower(PHP_OS)=='winnt'){
            $command = "ping -n 1 $address";
            exec($command, $output, $status);
        }else{
            $command = "ping -c 1 $address";
            exec($command, $output, $status);
        }
        if($status === 0){
            return true;
        }else{
            return false;
        }
    }

I use this function :

<?php
function is_ping_address($ip) {
    exec('ping -c1 -w1 '.$ip, $outcome, $status);
    preg_match('/([0-9]+)% packet loss/', $outcome[3], $arr);
    return ( $arr[1] == 100 ) ? false : true;
}