Home » Php » php – How can I allow a download to pause/resume?

php – How can I allow a download to pause/resume?

Posted by: admin July 12, 2020 Leave a comment


Normally, when I want to allow a user to download a file without revealing the exact location, I just use something like this to let them download the file:

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . $filename) . "\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($filename));

But if they are using a modern browser or other download client, and they pause the download and try to resume it, the script (assuming they are still authenticated or whatever) will resend the headers and the file contents from the beginning, thus breaking the download, and basically requiring the file to be redownloaded from the beginning.

How can I enable my script to compensate for paused (and consequentially, resumed) downloads?

How to&Answers:

Use php’s built-in fopen to open the file and then fseek to the right place (based on the range in the request header) and then return the partial file using fpassthru instead of using readfile.

You can find some example code in php under the comments for fread


You need to read the request headers like Range, If-Range, etc then seek to the correct location in the file. Normally a web-server would do this for you on an ordinary file. It’s a bit complex but here’s something that might get you started:



For the second link the code is in part 12