How to Implement Resumable File Downloads in PHP Using HTTP Range

This article explains the principle of HTTP range requests and provides step‑by‑step PHP code to enable resumable file downloads, covering header configuration, range parsing, validation, and partial content delivery for both private and dynamic resources.

21CTO
21CTO
21CTO
How to Implement Resumable File Downloads in PHP Using HTTP Range

Principle

Resumable download leverages the HTTP protocol’s ability to transfer a specific byte range of a resource instead of the whole file. By requesting only the needed part, the client can pause and later continue downloading from the exact point where it stopped.

Implementation

In PHP you first announce support for byte ranges with the Accept-Ranges: bytes header. Then read the Range request header (available in $_SERVER['HTTP_RANGE']) and determine the start and end positions, applying validation such as non‑negative start, end greater than start, and bounds within the file size.

header('Accept-Ranges: bytes');
$range = "0-".($content_length-1);
if (isset($_SERVER['HTTP_RANGE'])) {
    $range = $_SERVER['HTTP_RANGE'];
}

After validating the range, send the appropriate response headers, for example:

header('HTTP/1.1 206 Partial Content');
header('Accept-Ranges: bytes');
header("Content-Range: bytes $start-$end/$filesize");
header("Content-Length: $length");

Finally read and output the requested portion of the file. The status code must be 206, not 200.

Conclusion

Resumable downloads exploit HTTP partial content support, which can also be used for multi‑threaded downloading. Correctly setting the HTTP headers is essential; otherwise the downloaded file may become corrupted.

References

HTTP 1.1 Spec

HTTP Status: 206 Partial Content and Range Requests

PHP Resumable Download Server

Source: PHP
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPHTTP RangePartial ContentResumable Download
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.