Ping Site and Return Result in PHP

Ping site and return result in PHP

function urlExists($url=NULL)  
{
if($url == NULL) return false;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300){
return true;
} else {
return false;
}
}

This was grabbed from this post on how to check if a URL exists. Because Twitter should provide an error message above 300 when it is in maintenance, or a 404, this should work perfectly.

Pinging an IP address using PHP and echoing the result

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");

how to ping ip addresses in php and give results

$ip =   "127.0.0.1";
exec("ping -n 3 $ip", $output, $status);
print_r($output);

output looks like below

Array
(
[0] =>
[1] => Pinging 127.0.0.1 with 32 bytes of data:
[2] => Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
[3] => Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
[4] => Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
[5] =>
[6] => Ping statistics for 127.0.0.1:
[7] => Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),
[8] => Approximate round trip times in milli-seconds:
[9] => Minimum = 0ms, Maximum = 0ms, Average = 0ms
)

How can I ping a server port with PHP?

I think the answer to this question pretty much sums up the problem with your question.

If what you want to do is find out whether a given host will accept
TCP connections on port 80, you can do this:

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

For anything other than TCP it will be more difficult (although since
you specify 80, I guess you are looking for an active HTTP server, so
TCP is what you want). TCP is sequenced and acknowledged, so you will
implicitly receive a returned packet when a connection is successfully
made. Most other transport protocols (commonly UDP, but others as
well) do not behave in this manner, and datagrams will not be
acknowledged unless the overlayed Application Layer protocol
implements it.

The fact that you are asking this question in this manner tells me you
have a fundamental gap in your knowledge on Transport Layer protocols.
You should read up on ICMP and TCP, as well as the OSI Model.

Also, here's a slightly cleaner version to ping to hosts.

// Function to check response time
function pingDomain($domain){
$starttime = microtime(true);
$file = fsockopen ($domain, 80, $errno, $errstr, 10);
$stoptime = microtime(true);
$status = 0;

if (!$file) $status = -1; // Site is down
else {
fclose($file);
$status = ($stoptime - $starttime) * 1000;
$status = floor($status);
}
return $status;
}

Need to track PC down times using PHP ping and display time down D:HH:MM

Here is an example using a text file, as requested. A few notes:

  1. For simplicity, I suggest using CURL instead of exec as it should be a lot faster and more reliable. This checks for the HTTP status code "200" which means it returned a valid request.
  2. You will need to make sure your text file/s have the appropriate read & write permissions.
  3. I've updated this answer to also address your other question.

The initial text file in this example is named data.txt and contains the following:

p1|google.com|
p2|yahoo.com|
p2|amazon.com|

The following code will cycle through each server in the list, and update the records with the latest date if it's online.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="30">
</head>
<body>

<h1>PC Test Ping Status</h1>

<?php

function ping($addr) {
$ch = curl_init($addr);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//get response code
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($code === 200) {
return true;
}

return false;
}

$file = 'data.txt';
$servers = array_filter(explode("\n", file_get_contents($file)));
foreach ($servers as $key => $server) {
list($sname, $saddr, $suptime) = explode('|', $server);
if (ping($saddr)) {
echo "<p>$sname is online</p>";
$date = new DateTime();
$suptime = $date->format('Y-m-d H:i:s');
} else {
echo "<p>$sname is offline since: ";
if (trim($suptime) !== '') {
echo $suptime . '</p>';
} else {
echo 'unknown</p>';
}
}
$servers[$key] = implode('|', array($sname, $saddr, $suptime)) . "\n";
}
file_put_contents($file, $servers);

?>


</body>
</html>

php ping test and redirect

Note: Your code seems to work fine on Linux but not on windows. Checking a little further I noticed that windows does not provide -c option for ping, which causes it to return a different value than expected and your ping fails

exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($host)), $res, $rval);
return $rval === 0;

That seems to assume that the return value will be 0 from exec on success? But according to PHP Manual it will be

The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.
To get the output of the executed command, be sure to set and use the output parameter.

It appears like your comparison with returned value is the problem. What value does $rval contain?



Related Topics



Leave a reply



Submit