简体   繁体   中英

Download large files with PHP

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?

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 @NB mentions in his comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM