Downloading big files and writing it locally

前端 未结 2 2037
春和景丽
春和景丽 2021-02-11 07:31

which is the best way to download from php large files without consuming all server\'s memory?

I could do this (bad code):

$url=\'http://server/bigfile\'         


        
2条回答
  •  死守一世寂寞
    2021-02-11 08:05

    Here is a function I use when downloading large files. It will avoid loading the entire file into the buffer. Instead, it will write to the destination as it receives the bytes.

    function download($file_source, $file_target) 
    {
        $rh = fopen($file_source, 'rb');
        $wh = fopen($file_target, 'wb');
        if (!$rh || !$wh) {
            return false;
        }
    
        while (!feof($rh)) {
            if (fwrite($wh, fread($rh, 1024)) === FALSE) {
                return false;
            }
        }
    
        fclose($rh);
        fclose($wh);
    
        return true;
    }
    

提交回复
热议问题