4

I am working on a PHP script that makes an API call to a external site. However, if this site is not available or the request times out, I would like my function to return false.

I have found following, but I am not sure on how to implement it on my script, since i use "file_get_contents" to retrieve the content of the external file call.

Limit execution time of an function or command PHP

   $fp = fsockopen("www.example.com", 80);
if (!$fp) {
    echo "Unable to open\n";
} else {

    fwrite($fp, "GET / HTTP/1.0\r\n\r\n");
    stream_set_timeout($fp, 2);
    $res = fread($fp, 2000);

    $info = stream_get_meta_data($fp);
    fclose($fp);

    if ($info['timed_out']) {
        echo 'Connection timed out!';
    } else {
        echo $res;
    }

}

(From: http://php.net/manual/en/function.stream-set-timeout.php)

How would you adress such an issue? Thanks!

Community
  • 1
  • 1
Industrial
  • 41,400
  • 69
  • 194
  • 289

4 Answers4

2

I'd recommend using the cURL family of PHP functions. You can then set the timeout using curl_setopt():

curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2); // two second timeout

This will cause the curl_exec() function to return FALSE after the timeout.

In general, using cURL is better than any of the file reading functions; it's more dependable, has more options and is not regarded as a security threat. Many sysadmins disable remote file reading, so using cURL will make your code more portable and secure.

Lucas Oman
  • 15,597
  • 2
  • 44
  • 45
  • Pheew, the server doesn't allow cURL. I am going to try and see if i can get it running though. – Industrial Jan 13 '10 at 14:28
  • 1
    PHP probably just wasn't compiled with it. Sorry! If you're intent on using it, I'm sure you could convince your sysadmin to install it and disallow remote file access on security grounds. Honestly, I'm surprised he hasn't already (apologies if you're the sysadmin ;-) – Lucas Oman Jan 13 '10 at 14:42
  • Hi Lucas. Thanks for your help. No, im trying to get a hold of the system admin right now and see if I can sort it out when cURL is available! – Industrial Jan 13 '10 at 18:41
0

From the PHP manual for File_Get_Contents (comments):

<?php 
$ctx = stream_context_create(array( 
    'http' => array( 
        'timeout' => 1 
        ) 
    ) 
); 
file_get_contents("http://example.com/", 0, $ctx); 
?>
Jan Hančič
  • 53,269
  • 16
  • 95
  • 99
0
<?php
$fp = fsockopen("www.example.com", 80);

if (!$fp) {
    echo "Unable to open\n";
} else {
    stream_set_timeout($fp, 2); // STREAM RESOURCE, NUMBER OF SECONDS TILL TIMEOUT
    // GET YOUR FILE CONTENTS
}
?>
Jan Hančič
  • 53,269
  • 16
  • 95
  • 99
DBunting
  • 38
  • 6
0
<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 4);
if ($fp) {
    stream_set_timeout($fp, 2);
}
goat
  • 31,486
  • 7
  • 73
  • 96