1

I can't allow for file_get_contents to work more than 1 second, if it is not possible - I need to skip to next loop.

for ($i = 0; $i <=59; ++$i) {
$f=file_get_contents('http://example.com');

if(timeout<1 sec) - do something and loop next;
else skip file_get_contents(), do semething else, and loop next;
}

Is it possible to make a function like this?

Actually I'm using curl_multi and I can't fugure out how to set timeout on a WHOLE curl_multi request.

user1482261
  • 191
  • 3
  • 15
  • Use stream context to set the timeout to 1 second. See http://stackoverflow.com/questions/10236166/does-file-get-contents-have-a-timeout-setting – Oscar M. May 13 '14 at 17:16

2 Answers2

2

If you are working with http urls only you can do the following:

$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 1
    )
));

for ($i = 0; $i <=59; $i++) {
    file_get_contents("http://example.com/", 0, $ctx); 
}

However, this is just the read timeout, meaning the time between two read operations (or the time before the first read operation). If the download rate is constant, there should not being such gaps in the download rate and the download can take even an hour.

If you want the whole download not take more than a second you can't use file_get_contents() anymore. I would encourage to use curl in this case. Like this:

// create curl resource
$ch = curl_init();

for($i=0; $i<59; $i++) {

    // set url
    curl_setopt($ch, CURLOPT_URL, "example.com");

    // set timeout
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);

    //return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // $output contains the output string
    $output = curl_exec($ch);

    // close curl resource to free up system resources
    curl_close($ch);
}
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • 1
    why define the context again and again ... within the for loop? can it not be defined outside once and used inside the for loop? – Latheesan May 13 '14 at 17:19
  • @hek2mgl I'm actually using curl_setopt($curly[$id], CURLOPT_TIMEOUT, 1); for curl_multi with 5 different url request. But it can add up to 5 seconds. How can I set a 1 second timeout for WHOLE curl_multi request? – user1482261 May 13 '14 at 17:34
  • Unfortunately there is no option for this. Let me think of a workaround.. (Interesting question) – hek2mgl May 13 '14 at 17:41
  • 1
    A workaround will be using low level socket communication, where you have to implement HTTP on your own. Then you can use socket_select() to realize the timeout. I don't see a better solution at the moment. need to be AFK for a while. Tell me if you have updates on this or need more help – hek2mgl May 13 '14 at 18:01
1
$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 1
        )
    )
);
file_get_contents("http://example.com/", 0, $ctx); 

Source

Sammitch
  • 30,782
  • 7
  • 50
  • 77