Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I allow a download to pause/resume?

Tags:

http

php

download

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));
readfile("$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?

like image 688
Abraham Vegh Avatar asked May 24 '09 15:05

Abraham Vegh


2 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

like image 185
Alo Avatar answered Sep 21 '22 19:09

Alo


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:

http://forums.asp.net/t/1218116.aspx

http://www.notes411.com/dominosource/tips.nsf/0/480C4E3BE825F69D802571BC007D5AC9!opendocument

For the second link the code is in part 12

like image 23
SpliFF Avatar answered Sep 21 '22 19:09

SpliFF