Forum Moderators: coopster
I'm trying to write a basic script that will check a website responds to a HTTP request within 60 seconds. However, I'm not quite sure how to catch the time-out event.
Here is my code:
--------------------------------------------------------
<?php
$url = "mydomain.tld";
$found = "N";
$found = Check_response($url, $found);
if ($found == "N")
{
$email_msg = "The following site failed to respond after 60 seconds:\n\n";
$email_msg = $email_msg . "Site: [mydomain.tld...]
$email_msg = $email_msg . "Description: mydomain.tld\n";
$email_msg = $email_msg . "Date: " . date("D M j G:i:s T Y") . "\n\n";
$snd_2_email = "my.email@another.tld";
$email_from = "noreply@another.tld";
$email_subject = "WARNING: mydomain.tld failed to respond.";
mail($snd_2_email,$email_subject,$email_msg,"From:$email_from\r\nReply-To: webservices@mydomain.tld");
}
function Check_response ($url, $found)
{
set_time_limit(60);
$lines = file($url);
foreach ($lines as $line_num => $line)
{
if (strstr($line,"unique keyword from within the html")) { $found = "Y"; }
}
return $found;
}
?>
--------------------------------------------------------
Can anyone advise where I'm going wrong? All I get at the moment is a "Fatal error: Maximum execution time of 60 seconds exceeded in C:\localhost\checksite.php on line xx"
[edited by: Karma at 12:23 pm (utc) on Dec. 17, 2008]
I think the only way to catch the time-out event is to check the execution time of the Check_response function call, something like this:
// start counting seconds
$t1 = time();
// now let this function complete it's operation
// even if encountering a server timeout on the other end
$found = Check_response($url, $found);
if( (time() - $t1) > 60 ) // took longer than 60 seconds?
$found = "N"; // then consider the URL as not found
Hmm...set_time_limit returns a fatal_error if reached, thereby halting your scripts execution. So if you wanna restrict a procedure to a specific time duration, I don't think that's that's the function to use.
I agree with Outdo...your handle's too long dude. ;)
time() is the function to use, but I would recommend placing the conditional in the Check_response procedure:
function Check_response ($url, $found) {
$lines = file($url);
$start = time();
$duration = 60;
$end = $start + $duration;
foreach ($lines as $line_num => $line) {
if(time() <= $end){ // Keep checking!
if (strstr($line,"unique keyword from within the html")){
$found = "Y";
break;
}
} else { break; } // Timed out
}
return $found;
}
- M. Cold
$lines = file($url);
You check the time it takes to compare the content of $lines against the unique keyword, but not how long it takes to get this content.
But of course you could wrap the time check around the line
$lines = file($url);