What are the best practices for allowing users to pause and resume downloads using PHP and CURL?

When allowing users to pause and resume downloads using PHP and CURL, it is important to keep track of the download progress and allow users to resume the download from where it left off. One way to achieve this is by using the CURLOPT_RESUME_FROM option in CURL to specify the starting point of the download when resuming.

<?php

$download_url = 'http://example.com/file.zip';
$save_to = 'downloaded_file.zip';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $download_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Check if the file already exists and get its size
if (file_exists($save_to)) {
    $file_size = filesize($save_to);
    curl_setopt($ch, CURLOPT_RANGE, $file_size . '-');
}

$data = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
} else {
    $fp = fopen($save_to, 'a');
    fwrite($fp, $data);
    fclose($fp);
}

curl_close($ch);

?>