How can the completion of a file download be determined when using CURL to fetch a file from a remote server in PHP?
To determine the completion of a file download when using CURL in PHP, you can utilize the CURLOPT_NOPROGRESS option along with a custom progress function. This function will be called by CURL during the download process, allowing you to track the progress and determine when the download is complete.
// Initialize CURL session
$ch = curl_init();
// Set the URL to fetch the file from
curl_setopt($ch, CURLOPT_URL, 'http://example.com/file_to_download.zip');
// Set the option to not show progress
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
// Set a custom progress function
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function($resource, $download_size, $downloaded, $upload_size, $uploaded) {
if($downloaded == $download_size) {
echo 'Download complete!';
}
});
// Execute the CURL session
curl_exec($ch);
// Close the CURL session
curl_close($ch);