For some reason, I could not get millisecond (ms) granularity out of the CURLOPT_CONNECTTIMEOUT_MS and CURLOPT_TIMEOUT_MS. If I set timeout (as in my first post) to 2500 ms, I get return values of any value over 2 seconds. I am not sure why the _MS options in curl are not working properly (with ms granularity).
So, I changed the script to seconds instead of ms.... and will revisit this at a later date. If anyone has time to troubleshoot this, please do so and let me know. Thanks.
PHP Code:
<?php
$connecttimeout = 3;
$curltimeout = 4;
$heartbeat = "your.remote.server.com/file.html";
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $heartbeat);
// header
curl_setopt($ch, CURLOPT_HEADER, 1);
// connection timeout
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
// store results as the return of curl_exec
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// curl timeout
curl_setopt($ch, CURLOPT_TIMEOUT, $curltimeout);
// if HTML error 400 over over, fail
curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);
// set start time
$mtime = microtime();
$mtime = explode(' ', $mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
$output = curl_exec($ch);
//set end time
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
curl_close($ch);
$pattern = '/Your_Pattern/';
$errno = preg_match($pattern, $output, $matches, PREG_OFFSET_CAPTURE);
if($errno == 0){
$to = "your.email@yourdomain.com";
$subject = "Problem with Server";
$body = "There is a problem with the Server\n\n";
$body .= "This script executed in " .$totaltime. " seconds.";
$header = "From: root@yourdomain.com\r\n";
$header .= "Reply-To: root@yourdomain.com\r\n";
$header .= "Return-Path: root@yourdomain.com\r\n";
$success = mail($to, $subject, $body, $header);
}
?>