Large file download script

Discussion in 'PHP' started by SGBoise, Aug 10, 2009.

  1. #1
    Hello,

    I'm using a script that allows my clients to download files from my store. The problem I'm running into is that for some reason the download stops at around 5 minutes. I'm guessing it's hitting the max_execute_limit set by the web host.

    Below is the code that I'm currently using. Can anyone suggestion a different method to allow people to download large files?

    What I think would be if I could redirect the user to the actual file once I validate that the person has access to the file but that would mean giving the person direct access to the folder which I don't want to do.

    function readfile_chunked($file_name,$ret_bytes=true) {
        // important for large files
        set_time_limit(0);
        // determine memory limit
        //$memory_limit = (int)get_cfg_var('memory_limit');
        //if($memory_limit==0) $memory_limit = 1;
        $memory_limit = 1;
        $chunksize = $memory_limit*(1024*1024);
        $buffer = '';
        $cnt =0;
        $handle = fopen($file_name, 'rb');
       if ($handle === false) {
           return false;
       }
       while (!feof($handle)) {
           $buffer = fread($handle, $chunksize);
           echo $buffer;
           ob_flush();
           flush();
           if ($retbytes) {
               $cnt += strlen($buffer);
           }
       }
           $status = fclose($handle);
           exit;
       if ($retbytes && $status) {
           return $cnt;
       }
       return $status;
    }
    PHP:
    Thanks in advance.
     
    SGBoise, Aug 10, 2009 IP
  2. Dennis M.

    Dennis M. Active Member

    Messages:
    119
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    58
    #2
    Too bad I have to get going to bed to be up early or I would play around with this and give you a better solution. However, you could try copying the file to a location where you can give a direct link then use PHP's unlink(); command to remove the file after the user has downloaded it. The most effective way to run the unlink would be from a script running on cron that maybe takes file names from a DB and removes them all every 30 minutes to an hour (run the script every 30 minutes, but have a time in DB so if a user downloads a file 1min before cron runs, they can continue their download). Maybe if I have a chance tomorrow I'll come back to this one. Very good question :) If someone else doesn't come up with a solution, I wish you the best of luck and will check back when I have time tomorrow to see if I can give you a great solution!

    Regards,
    Dennis M.
     
    Dennis M., Aug 10, 2009 IP