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.

1

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

why define the context again and again ... within the for loop? can it not be defined outside once and used inside the for loop?
@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?
Unfortunately there is no option for this. Let me think of a workaround.. (Interesting question)
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
1
$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 1
        )
    )
);
file_get_contents("http://example.com/", 0, $ctx); 

Source

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.