我正在尝试获取远程文件并强制同时将其下载到用户.
我无法粘贴代码,代码太长.但curl函数有效,但问题是它没有输出任何东西,直到它首先获取远程文件然后它强制下载到用户.
我无法粘贴代码,代码太长.但curl函数有效,但问题是它没有输出任何东西,直到它首先获取远程文件然后它强制下载到用户.
我用它来告诉curl返回一个回调
curl_setopt($ch,CURLOPT_READFUNCTION,'readCallback');
现在在我的readCallback函数中我这样做:
function readCallback($curl,$stream,$maxRead){ $read = fgets($stream,$maxRead); echo $read; return $read; }
试试这个,它将使用curl来获取文件的总大小然后下载代理它的文件的部分块给用户,这样就没有等待curl首先下载它,我用avi,mp4,mp3测试了这个和一个exe,希望它有所帮助:
<?PHP $file = 'http://example.com/somefile.mp3'; download($file,2000); /* Set Headers Get total size of file Then loop through the total size incrementing a chunck size */ function download($file,$chunks){ set_time_limit(0); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-disposition: attachment; filename='.basename($file)); header('Cache-Control: must-revalidate,post-check=0,pre-check=0'); header('Expires: 0'); header('Pragma: public'); $size = get_size($file); header('Content-Length: '.$size); $i = 0; while($i<=$size){ //Output the chunk get_chunk($file,(($i==0)?$i:$i+1),((($i+$chunks)>$size)?$size:$i+$chunks)); $i = ($i+$chunks); } } //Callback function for CURLOPT_WRITEFUNCTION,This is what prints the chunk function chunk($ch,$str) { print($str); return strlen($str); } //Function to get a range of bytes from the remote file function get_chunk($file,$start,$end){ $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$file); curl_setopt($ch,CURLOPT_RANGE,$start.'-'.$end); curl_setopt($ch,CURLOPT_BINARYTRANSFER,1); curl_setopt($ch,CURLOPT_WRITEFUNCTION,'chunk'); $result = curl_exec($ch); curl_close($ch); } //Get total size of file function get_size($url){ $ch = curl_init(); curl_setopt($ch,$url); curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true); curl_setopt($ch,CURLOPT_RETURNTRANSFER,CURLOPT_HEADER,CURLOPT_NOBODY,true); curl_exec($ch); $size = curl_getinfo($ch,CURLINFO_CONTENT_LENGTH_DOWNLOAD); return intval($size); } ?>