joseagaleanoc
joseagaleanoc

Reputation: 615

How check if succesfull cmd ping in php

how can I check if a php ping returned succesfull or failed using php exec, I have in mind something with a while loop but I'm not sure if ts the best approach, I tried:

exec('ping www.google.com', $output)

but I would have to do a var_dump($output); to see the results, I want for each line the ping command returns to check it

$i = 2;
while(exec('ping www.google.com', $output)) {
  if($output) {
     echo 'True';
  } else {
     echo 'False';
  }
}

I know this code is WRONG but its kind of what I need, if any of you could give me a head start on how to do it or suggestions I would really appreciate it....THANKS!!

Upvotes: 1

Views: 865

Answers (2)

Mr.Web
Mr.Web

Reputation: 7176

This should do it:

if(exec('ping http://www.google.com')) {
 echo 'True';
} else {
 echo 'False';
}

I suggest you could use CUrl See Manual but that all depends upon what you are trying to achieve.

Provide more data if needed.

NOTE

You are to use http:// before google.com as that's needed in order to make the ping.

Upvotes: 3

TravisO
TravisO

Reputation: 9550

It's probably faster and more efficient and just do it within PHP, instead of exec'ing a shell

$host = '1.2.3.4'; 
$port = 80; 
$waitTimeoutInSeconds = 1; 
if($fp = fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds)){   
   // It worked 
} else {
   // It didn't work 
} 
fclose($fp);

Also some servers will have EXEC disabled for security reasons, so your method won't work on every server setup.

Upvotes: 1

Related Questions