PHP curl下载文件向浏览器输出

需要用到的CURLOPT_WRITEFUNCTION回调方式

// 向浏览器输出下载文件
$url = 'https://public-filelist.oss-cn-hangzhou.aliyuncs.com/MicrosoftOffice2010%E7%A0%B4%E8%A7%A3%E7%89%88.zip';
$ch  = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, ['user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 3600);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 20971520);
$flag=0;
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch ,$str) use (&$flag){
    $len = strlen($str);
    $flag++;
    $type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    if($flag==1){
        $size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
        $type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        $httpcode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        header("HTTP/1.1 ".$httpcode);
        header("Content-Type: ".$type);
        header("Content-Length: ".$size);
        header('Content-Transfer-Encoding: binary');
        header('Cache-Control:max-age=2592000');
        header('Content-Disposition: attachment; filename="MicrosoftOffice2010破解版.zip"'); 
    }
    echo $str;
    return $len;
});
$output = curl_exec($ch);

你可能感兴趣的:(PHP curl下载文件向浏览器输出)