Jeffrey Muller
Jeffrey Muller

Reputation: 850

simultaneously download on server and on user

I am currently developing an application in PHP in which my server (a dedicated server) must to download a file, and the user should download the file in same time.

Here is an example :

I already solved the problem :"If the user downloads the file faster than the server..". But I didn't know how to make a php script in which the user is gonna to download the full file (it means that the size must be the full size of the file, not the size it's currently downloaded at the time A+3seconds). I already make that :

header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename="'.$data['name'].'";'); 
header('Content-Transfer-Encoding: binary'); 
header('Content-Length: '.$data['size']);
readfile($remoteFile);

But it doesn't work, the user is gonna download just the size it is currently on the server (which corrupt the file) and not the full file...

If you have any solution, thank you.

Upvotes: 2

Views: 146

Answers (3)

Alix Axel
Alix Axel

Reputation: 154523

Expanding on @Tom answer, you can use cURL to greatly simplify the algorithm by using the CURLOPT_HEADERFUNCTION and CURLOPT_READFUNCTION callbacks - see curl_setopt().

Upvotes: 1

goat
goat

Reputation: 31813

Don't send the content-length header. It's not required assuming you're using http 1.1(your webserver almost certainly does). Drawback is their browser cant show download time/size remaining.

Upvotes: -1

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29975

You could probably pipe the file manually, by opening the connection and reading until you're past all headers. Then once you've figured out the Content-Length, send that to the user and just echo all remaining data you get (do use flush() and avoid output buffers).

Pseudocode(-ish):

open the file
# grab headers
while you didn't get all HTTP headers:
    read more
look for the Content-Length header
send the Content-Length header

# grab the file
while the rest of the request isn't done
    read more
    send it to the user
    flush the buffers

done

Upvotes: 3

Related Questions