views:

358

answers:

4

Hi guys,

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.

http://stackoverflow.com/questions/1176497/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!

+1  A: 

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č
This does not take the timeout in account, have no idea of why though.
Industrial
+1  A: 

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
Pheew, the server doesn't allow cURL. I am going to try and see if i can get it running though.
Industrial
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
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
A: 
<?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
}
?>
DBunting
dont know why it wont recognize newlines
DBunting
Hi! The timeout doesn't work here. I only reach the total max_execution time set by PHP.ini 60 seconds later if the site isn't available...
Industrial
A: 
<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 4);
if ($fp) {
    stream_set_timeout($fp, 2);
}
chris