Pinging an IP address using PHP and echoing the result

Bernard picture Bernard · Nov 6, 2011 · Viewed 103.3k times · Source

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.

Answer

maraspin picture maraspin · Nov 6, 2011

NOTE: Solution below does not work on Windows. On linux exec a "which ping" command from the console, and set command path (of the suggested exec call) accordingly

I think you want to check the exit status of the command, whereas shell_exec gives you full output (might be dangerous shall command output change from command version to version. for some reason). Moreover your variable $ip is not interpreted within single quotes. You'd have to use double ones "". That might be the only thing you need to fix in order to make it work.

But I think following code can be more "portable". IMHO it is in fact better to catch the exit status, rather than trying to parse result string. IMHO it's also better to specify full path to ping command.

<?php
function pingAddress($ip) {
    $pingresult = exec("/bin/ping -n 3 $ip", $outcome, $status);
    if (0 == $status) {
        $status = "alive";
    } else {
        $status = "dead";
    }
    echo "The IP address, $ip, is  ".$status;
}

pingAddress("127.0.0.1");