How can the Range header be utilized in PHP to allow users to resume downloads from where they left off?

When users download large files, it can be frustrating if the download is interrupted and they have to start over from the beginning. By utilizing the Range header in PHP, we can allow users to resume downloads from where they left off by specifying the byte range they want to download.

$file = 'path/to/your/file.ext';

if (isset($_SERVER['HTTP_RANGE'])) {
    $range = $_SERVER['HTTP_RANGE'];
    $size = filesize($file);
    $start = 0;
    $end = $size - 1;

    header('HTTP/1.1 206 Partial Content');
    header('Accept-Ranges: bytes');

    if (preg_match('/bytes=(\d+)-(\d+)?/', $range, $matches)) {
        $start = intval($matches[1]);
        $end = isset($matches[2]) ? intval($matches[2]) : $size - 1;
    }

    header('Content-Length: ' . ($end - $start + 1));
    header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
    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) {
            $buffer = fread($fp, $end - $p + 1);
        } else {
            $buffer = fread($fp, 8192);
        }

        echo $buffer;
        ob_flush();
        flush();
    }

    fclose($fp);
} else {
    header('HTTP/1.1 200 OK');
    header('Content-Length: ' . filesize($file));
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');

    readfile($file);
}