php批量下載文件


  最近用codeigniter開發一個圖片網站,發現單文件下載很容易實現,批量下載的話,就有點麻煩。

  普通php下載比較簡單,比如我封裝的一個函數:

function shao_download($filename = '', $file_path = '')
{
    $fp=fopen($file_path,"r");
    $file_size=filesize($file_path);
    //下載文件需要用到的header
    Header("Content-type: application/octet-stream");
    Header("Accept-Ranges: bytes");
    Header("Accept-Length:".$file_size);
    Header("Content-Disposition: attachment; filename=".$filename);
    $buffer=1024;
    $file_count=0;
    //向瀏覽器返回數據
    while(!feof($fp) && $file_count<$file_size){
      $file_con=fread($fp,$buffer);
      $file_count+=$buffer;
      echo $file_con;
    }
    fclose($fp); 
}

 

  

  以下是參考網上的例子,編寫的一個多文件下載測試文件,遇到同樣問題而不知道如何處理的朋友們可以參考下。

  思路如下:

  ① 把要下載的圖片信息組合到$imgs數組中

  ② 把要下載的圖片打包成zip壓縮包

  ③ 下載壓縮包,刪除服務器上的臨時zip文件

<?php
$imgs[] = 'http://demo.pic.com/column_f/large/IMG_Af8P_15.jpg';
$imgs[] = 'http://demo.pic.com/column_f/large/IMG_l89P_08.jpg';

$filename = 'tmp.zip';

$zip = new ZipArchive();
$zip->open($filename, ZipArchive::OVERWRITE);

foreach ($imgs as $key=>$vo) {
    $fileData = file_get_contents($vo);
    if ($fileData) {
        $zip->addFromString($key.'.jpg', $fileData);
    }
}


$zip->close();

$file = fopen($filename, "r");
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length: " . filesize($filename));
Header("Content-Disposition: attachment; filename=imgages.zip");
//一次只傳輸1024個字節的數據給客戶端
$buffer = 1024; //
while (!feof($file)) {
    //將文件讀入內存
    $file_data = fread($file, $buffer);
    //每次向客戶端回送1024個字節的數據
    echo $file_data;
}
fclose($file);
unlink($filename); //刪除文件

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM