How can ranges be helpful in resuming downloads of large files in PHP?
When downloading large files in PHP, it is important to handle interruptions or failures gracefully by allowing the download to resume from where it left off. This can be achieved by using HTTP range requests to download the file in chunks. By specifying the range of bytes to download, the download can be resumed without starting from the beginning each time.
// Set the file to be downloaded
$file = 'large_file.zip';
// Check if the file exists
if (file_exists($file)) {
// Set headers for resuming download
header('Accept-Ranges: bytes');
// Handle range requests
if (isset($_SERVER['HTTP_RANGE'])) {
$range = $_SERVER['HTTP_RANGE'];
$range = str_replace('bytes=', '', $range);
$range = explode('-', $range);
$start = intval($range[0]);
$end = intval($range[1]);
$length = filesize($file);
header('HTTP/1.1 206 Partial Content');
header('Content-Length: ' . ($end - $start + 1));
header('Content-Range: bytes ' . $start . '-' . $end . '/' . $length);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
$fp = fopen($file, 'rb');
fseek($fp, $start);
while (!feof($fp) && ($p = ftell($fp)) <= $end) {
if ($p + 8192 > $end) {
// In case the end is near
echo fread($fp, $end - $p + 1);
} else {
echo fread($fp, 8192);
}
flush();
}
fclose($fp);
exit;
} else {
// Full download
header('Content-Length: ' . filesize($file));
readfile($file);
}
} else {
// File not found
echo 'File not found.';
}