How to implement downloads through PHP with resumption and multi-stream capability
In present web programming practice there often arises the task of implementing downloads through PHP (or other scripting languages). The task itself is not very hard. PHP includes the function virtual() which can be used for this purpose. But this realization has one problem: there is no way to resume aborted downloads and no way to download files in a multi-stream manner. Below you will find a sample PHP code which solves these problems. But, let’s start with some theory behind the code.First of all we should discuss the mechanism of how this behavior works. This functionality is a part of HTTP 1.1 standart RFC2616 (see w3c specification: http://www.w3.org/Protocols/rfc2616/rfc2616.html ).
So as we can see from the specifications in the RFC document, resuming and multi-streaming download support is mostly handled by following HTTP headers: “Content-Length” and “Content-Range”. Additionally response status header “HTTP/1.1 206 Partial Content” defined for this type of requests/responses. First download request is no different from standard request. The main “magic” will begin with subsequent requests, when user (specifically the user web browser/download client) requests download resumption or the next part of multi-stream download. The users’ client sends to the web server a request with supplied position to determine where it wants to start the download. Commonly this position is equal to where the download was aborted. Also, by using this functionality, most download clients organize multi-streamed downloading through sending to the server a few requests at the same time, so multi-streamed downloading technically is the same thing as resumption of download.
After web server receives such a request, it should answer either with standard status “200″, what in fact means “download resumption is not supported” (this is how the implementation of virtual() function works), or after handling received data, server should reply with “206″ status code, content length, content range, and, of course, content itself. All this functionality is supported by default in most recent HTTP servers, but as said above, sometimes this content should be given to client through a PHP script (for example after authorization).
