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 :)

Tomer Lichtash
  • 9,002
  • 16
  • 55
  • 71

8 Answers8

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.

0stone0
  • 34,288
  • 4
  • 39
  • 64
Tyler Carter
  • 60,743
  • 20
  • 130
  • 150
  • if you need SSL then talke a look at this post https://stackoverflow.com/questions/4372710/php-curl-https – eballo Oct 02 '17 at 14:58
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);  
karim79
  • 339,989
  • 67
  • 413
  • 406
  • 9
    that's no good return values. why not return 0/false/null on failure and an integer representing the milliseconds on success? – Philippe Gerber Aug 06 '09 at 14:52
  • 2
    @Philippe Gerber - Because I didn't write it, but those are good suggestions. – karim79 Aug 06 '09 at 14:57
  • 5
    Ping is working on ICMP protocol, there are no such thing like 'port'. You can ping a host with 0 open tcp ports. – deejayy Dec 15 '11 at 07:05
  • 1
    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 known – Natasha Jan 17 '13 at 05:50
  • @karim79 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. – Shahid Rafiq Sep 05 '17 at 05:20
  • I put a fake domain but still get the result. do u know why ? the result i mean, it should return ms right ? – MaXi32 Jun 11 '20 at 17:51
11

Using shell_exec:

<?php
$output = shell_exec('ping -c1 google.com');
echo "<pre>$output</pre>";
?>
Elzo Valugi
  • 27,240
  • 15
  • 95
  • 114
  • 4
    You should use `ping -c1 host` or something on Linux. Plain `ping host` will not return there. – Michas May 13 '10 at 13:51
  • better yet: `if ( 0 != ( $_result = \`ping -q -c1 google.com >/dev/null 2>&1 ; echo $?\` ) ) { echo 'Fail.'; }` – lucifurious Feb 27 '13 at 17:20
  • good but many production sites always disable PHP shell_exec function for security reason. – MaXi32 Jun 11 '20 at 17:52
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.';
}
geerlingguy
  • 4,682
  • 8
  • 56
  • 92
6

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

Philippe Gerber
  • 17,457
  • 6
  • 45
  • 40
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;
}
42abc
  • 11
  • 1
  • 3
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;
}
icc97
  • 11,395
  • 8
  • 76
  • 90
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;
    } 


Fthr
  • 769
  • 9
  • 10