Search code examples
phpdownloadlarge-files

using php to download files, not working on large files?


I'm using php to download files, rather than the file itself opening in a new window. It seems to work ok for smaller files, but does not work for large files (I need this to work on very large files). Here's the code I have to download the file:

function downloadFile($file) {   
    if (file_exists($file)) {         
        //download file
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: '.filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;   
    };    
};

But when I try to download a large file (example 265mb) the browser tells me that it can't find the file? The files are definately on the server, and the script works fine for the smaller files. Is there any way of downloading large files similar to what I already have?


Solution

  • PHP has limits on how long a script can run, and how much memory it can use. It's possible that the script is timing out before it has completed, or is using up too much memory by reading in the large file.

    Try tweaking the max_execution_time and memory_limit variables in php.ini. If you don't have access to php.ini, try the set_time_limit and/or ini_set functions.