0

I'm using jQuery with PHP. I've written a simple download function with PHP:

function downloadFile($sFile){
        #Main function
        header('Content-Type: '.mime_content_type($sFile)); 
        header('Content-Description: File Transfer');
        header('Content-Length: ' . filesize($sFile)); 
        header('Content-Disposition: attachment; filename="' . basename($sFile) . '"');
        readfile($sFile);
    }

I can download a file through this script, but if it's a large files(like 1GB), the readfile function needs his time until the download start. So i have to wait about a minute or something, until the download really starts. Any idea how to optimze my script, so the download starts immediately?

Sylnois
  • 1,589
  • 6
  • 23
  • 47
  • 2
    Send the file in smaller chunks. That means, don't use readfile, use fopen/fread combination and echo out every few kilobytes. Check out this URL for details of implementation: http://stackoverflow.com/questions/14664409/fread-a-lot-slower-for-downloads-than-readfile – N.B. Sep 02 '13 at 08:48
  • See it here -- https://stackoverflow.com/questions/47827768/how-to-download-large-files-with-php/47827769#47827769 – Oleg Uryutin Dec 15 '17 at 07:42

1 Answers1

0

You could configure Apache to set the proper headers in your .htaccess file. Then, you could link directly to the file instead of the PHP page. This will also reduce server load.

Of course, if the PHP script performs functions other than just setting headers (such as authentication) then this is not an option. You will have to pass the file through PHP in chunks as @N.B. mentions in his comment.

dotancohen
  • 30,064
  • 36
  • 138
  • 197