Using php to ping a website
<p>I want to create a php script that will ping a domain and list the response time along with the total size of the request. This will be used for monitoring a network of websites. I took  a pass at it with curl. Can you think of a better option?</p>

<p>This is mostly all from comments on php.net and more of a proof of concept then anything else. I know it's not the cleanest code.</p>

<pre><code>function curlTest2($url) {

 clearstatcache();

 $return = '';

 if(substr($url,0,4)!="http") $url = "http://".$url;

 $userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';

 $ch = curl_init($url);
 curl_setopt($ch, CURLOPT_HEADER, 1);
 curl_setopt($ch, CURLOPT_NOBODY, 1);
 curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 15);
 curl_setopt($ch, CURLOPT_FAILONERROR, 1);
 curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);

 $execute = curl_exec($ch);

 // Check if any error occured
 if(!curl_errno($ch)) {
  $bytes   = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
  $total_time = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
  $return = 'Took ' . $total_time . ' / Bytes: '. $bytes;        
 } else {
  $return = 'Error reaching domain';
 }
 curl_close($ch);

 return $return;

}
</code></pre>

<p>And here is one using fopen</p>

<pre><code>function fopenTest($link) {

 if(substr($link,0,4)!="http"){ 
 $link = "http://".$link;
 }

 $timestart = microtime();

 $churl = @fopen($link,'r');

 $timeend = microtime();
 $diff = number_format(((substr($timeend,0,9)) + (substr($timeend,-10)) - (substr($timestart,0,9)) - (substr($timestart,-10))),4);
 $diff = $diff*100;

 if (!$churl) {
  $message="Offline";
 }else{
  $message="Online. Time : ".$diff."ms ";
 }

 fclose($churl); 

 return  $message;

}
</code></pre>
