1 year ago

#330200

test-img

MatKus

set timeout for slow download using file_get_content or CURL

I'm downloading files from external servers. In most cases everything works fine, but with 2 servers i have problem. Sometimes, randomly, they send files very slow.

I don't get timeout, because i connect to server and it never breaks connection, but sometimes it can send 300KB file for 3 hours.

Is there way to tell PHP to stop downloading file it it takes more than some time?

Right now my code looks like this:

function downloadFileMethod1($url)
{
    $headers[] = "user-agent: Mozilla/5.0 (Linux; Android 6.0.1; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Mobile Safari/537.36";
    //$headers[] = "Connection: close";
    $stream_context_params= [
        'http' => [
            "method"          => 'GET',
            "header"          => implode("\r\n", $headers),
            "ignore_errors"   => TRUE,
            'timeout'         => 5,
            'follow_location' => TRUE,
            'max_redirects'   => 20,
        ],
    ];
    $context = stream_context_create($stream_context_params);
    return file_get_contents($url, FALSE, $context);
}

Here I'm using file_get_contents, but exactly same problem appears, if I'm using CURL.

If server will not respond, there will be some connection problem, I get timeout after 5 seconds and it's fine, but if transfer is very slow, but stable, I don't get any timeout ever.

Of course i could set max_execution_time, but this will break whole code, not just that one download, and i don't want to break code that has to execute after downloading this file.

And i can't exclude some files, because i never know what fill will cause problem. Sometimes it's first file, sometime i can download 1500 files before problem will occur. And sometimes just one file will be so slow, and then another one will work fine.

Is there way to set maximum downloading time for file?

php

download

timeout

file-get-contents

0 Answers

Your Answer

Accepted video resources