download files asynchrony in php

To download files asynchronously in PHP, you can use the CURL library. Here's an example code:

main.php
function downloadFileAsync($url, $path)
{
    $fp = fopen($path, "w");
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_NOPROGRESS, false);
    curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function($resource, $download_size, $downloaded, $upload_size, $uploaded){
        echo "\r" . round(($downloaded / $download_size) * 100, 2) . "% complete";
    });
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
}
602 chars
17 lines

This function takes two parameters: the URL of the file to download and the path where to save the file locally. It initializes a CURL request with the necessary options to download the file asynchronously and show progress in the console using the CURLOPT_PROGRESSFUNCTION option.

To use this function, you can simply call it like this:

main.php
downloadFileAsync("http://example.com/file.zip", "/path/to/local/file.zip");
77 chars
2 lines

This will start the file download asynchronously, and you can continue executing other code while the file is being downloaded.

gistlibby LogSnag