0

This is my code for file download:

            set_time_limit(0);
            header('Set-Cookie: fileDownload=true; path=/'); //used for the file download library for the browser client https://github.com/johnculviner/jquery.fileDownload . Remove if the library isn't used anymore
            header('Content-disposition: attachment; filename="' . $file->getName() . '"');
            header('Content-Type: application/octet-stream');
            header("Pragma: public");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            while (!feof($stream)) {
                    echo fread($stream, 8192);
                    ob_flush();
                    flush();
            }

The problem is that when i open the url for the file and the file has size bigger than 100MB for example, there is a huge delay for the download to actually start. Can someone explain to me what's causing it and how can be fixed? EDIT: The problem is solved. It turned out that my web server had an output buffering turned on by default.

user1113314
  • 803
  • 1
  • 10
  • 24
  • Are you sure the stream you are reading from hasn't already buffered the file? Also, you can pin-point the slow part by logging some timestamps before and after some operations. – stormbreaker Nov 30 '13 at 17:30
  • I'm reading from a MongoDB gridFS resource stream so there is no buffering. And yes, I've measured the execution time and it is concentrated in the file output code. – user1113314 Nov 30 '13 at 17:47

1 Answers1

1

There is a large delay because you make PHP load the entire file and output it all in one batch. See this question Streaming a large file using PHP to find out how to stream the data instead of serving it in one big load.

Community
  • 1
  • 1
  • Im not loading the whole file in the memory. Im loading it in chunks, just as it is done in the given StackOverflow example. The problem remains. – user1113314 Nov 28 '13 at 21:50
  • @user1113314 have you tried using x-sendfile as is described in the bottom of this document http://teddy.fr/2007/11/28/how-serve-big-files-through-php/ ? –  Nov 28 '13 at 23:28
  • I can't because I'm not using the file system. I'm getting the resource stream from MongoDB – user1113314 Nov 29 '13 at 09:53