tags:

views:

596

answers:

4

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

+2  A: 

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
that's no good return values. why not return 0/false/null on failure and an integer representing the milliseconds on success?
Philippe Gerber
@Philippe Gerber - Because I didn't write it, but those are good suggestions.
karim79
+1  A: 
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.

Chacha102
+1  A: 

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

Philippe Gerber
A: 

Using shell_exec:

<?php
$output = shell_exec('ping google.com');
echo "<pre>$output</pre>";
?>
Elzo Valugi
You should use `ping -c1 host` or something on Linux. Plain `ping host` will not return there.
Michas