Ping site and return result in PHP
Asked Answered
T

8

28

I'd like to create a small IF procedure that will check if Twitter is available (unlike now, for example), and will return true or false.

Help :)

Trochee answered 6/8, 2009 at 14:0 Comment(1)
instead of ping, cant you make a http request?Haplology
D
50
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);  

    return $httpcode >= 200 && $httpcode < 300;
}  

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.

Dvorak answered 6/8, 2009 at 14:3 Comment(1)
if you need SSL then talke a look at this post https://mcmap.net/q/240287/-php-curl-amp-httpsSmiley
B
25

Here's one:

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?lngWId=8&txtCodeId=1786

Another:

function ping($host, $port, $timeout) { 
  $tB = microtime(true); 
  $fP = fSockOpen($host, $port, $errno, $errstr, $timeout); 
  if (!$fP) { return "down"; } 
  $tA = microtime(true); 
  return round((($tA - $tB) * 1000), 0)." ms"; 
}

//Echoing it will display the ping if the host is up, if not it'll say "down".
echo ping("www.google.com", 80, 10);  
Bedaub answered 6/8, 2009 at 14:2 Comment(6)
that's no good return values. why not return 0/false/null on failure and an integer representing the milliseconds on success?Arithmetic
@Philippe Gerber - Because I didn't write it, but those are good suggestions.Bedaub
Ping is working on ICMP protocol, there are no such thing like 'port'. You can ping a host with 0 open tcp ports.Wonderstricken
fsockopen is not working on local host when internet is not connected.. it shows this error Warning: fsockopen(): php_network_getaddresses: getaddrinfo failed: No such host is knownGinglymus
@Bedaub Thanks a lot. Had to use it in emergency directly in production mode on a project in very short notice. Used it as it is. Saved my life.Soucy
I put a fake domain but still get the result. do u know why ? the result i mean, it should return ms right ?Immerse
B
11

Using shell_exec:

<?php
$output = shell_exec('ping -c1 google.com');
echo "<pre>$output</pre>";
?>
Brause answered 6/8, 2009 at 14:46 Comment(3)
You should use ping -c1 host or something on Linux. Plain ping host will not return there.Dorsiventral
better yet: if ( 0 != ( $_result = `ping -q -c1 google.com >/dev/null 2>&1 ; echo $?` ) ) { echo 'Fail.'; }Hemihydrate
good but many production sites always disable PHP shell_exec function for security reason.Immerse
A
7

Another option (if you need/want to ping instead of send an HTTP request) is the Ping class for PHP. I wrote it for just this purpose, and it lets you use one of three supported methods to ping a server (some servers/environments only support one of the three methods).

Example usage:

require_once('Ping/Ping.php');
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency) {
  print 'Latency is ' . $latency . ' ms';
}
else {
  print 'Host could not be reached.';
}
Auricula answered 10/12, 2012 at 3:13 Comment(0)
A
6

ping is available on almost every OS. So you could make a system call and fetch the result.

Arithmetic answered 6/8, 2009 at 14:36 Comment(0)
J
1

Another solution :

Use get_headers and compare the http code.

function ping(string $url): bool
{
   $headers = get_headers($url);
   $httpCode = intval(substr($headers[0], 9, 3));

   return $httpCode >= 200 && $httpCode < 300;
}
Jezebel answered 6/10, 2022 at 14:48 Comment(0)
V
0

With the following function you are just sending the pure ICMP packets using socket_create. I got the following code from a user note there. N.B. You must run the following as root.

Although you can't put this in a standard web page you can run it as a cron job and populate a database with the results.

So it's best suited if you need to monitor a site.

function twitterIsUp() {
    return ping('twitter.com');
}

function ping ($host, $timeout = 1) {
    /* ICMP ping packet with a pre-calculated checksum */
    $package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost";
    $socket = socket_create(AF_INET, SOCK_RAW, 1);
    socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0));
    socket_connect($socket, $host, null);

    $ts = microtime(true);
    socket_send($socket, $package, strLen($package), 0);
    if (socket_read($socket, 255)) {    
        $result = microtime(true) - $ts;
    } else {
        $result = false;
    }
    socket_close($socket);

    return $result;
}
Ventail answered 12/11, 2013 at 12:3 Comment(0)
T
0

this is php code I used, reply is usually like this:

    2 packets transmitted, 2 received, 0% packet loss, time 1089ms

So I used code like this:

  

    $ping_how_many = 2;
    $ping_result = shell_exec('ping -c '.$ping_how_many.' bing.com');
    if( !preg_match('/'.$ping_how_many.' received/',$ping_result) ){
       echo 'Bad ping result'. PHP_EOL;
        // goto next1;
    } 


Twinned answered 26/8, 2016 at 11:18 Comment(2)
this might lead to ping: icmp open socket: Permission denied. To solve this, SELinux must be PermissiveNewcomb
and also not a good idea for production site to use shell_exec in php.Immerse

© 2022 - 2024 — McMap. All rights reserved.