What are the implications of using HTTP_RANGE in the context of PHP file downloads?
When using HTTP_RANGE in PHP file downloads, it allows for partial content downloads, which can improve download speeds for large files. However, it is important to properly handle and validate the range requests to prevent security vulnerabilities such as unauthorized access to sensitive files.
$filePath = 'path/to/file.pdf';
if (file_exists($filePath)) {
$fileSize = filesize($filePath);
$handle = fopen($filePath, 'rb');
$range = $_SERVER['HTTP_RANGE'] ?? null;
if ($range) {
header('HTTP/1.1 206 Partial Content');
list($start, $end) = explode('-', str_replace('bytes=', '', $range));
fseek($handle, $start);
$length = $end - $start + 1;
header("Content-Length: $length");
header("Content-Range: bytes $start-$end/$fileSize");
} else {
header('HTTP/1.1 200 OK');
header("Content-Length: $fileSize");
}
header('Content-Type: application/pdf');
fpassthru($handle);
fclose($handle);
} else {
header('HTTP/1.1 404 Not Found');
}