2012-07-10 31 views
4

全部, 我允許用戶將圖像上傳到我的網站。對於該用戶,我想要下載用戶從我的網站上傳到我的網站的所有圖像。所以我想基本上有一個用戶名下拉列表,然後當我選擇一個查詢我的數據庫,並獲得他們下載的所有圖像。這部分是沒有問題的。從我的網站下載目錄中的所有文件到一個Zip文件夾

我的問題是我怎樣才能通過這些文件,並把它們放到一個zip文件夾,然後下載zip文件夾(如果可能的話)。

關於如何去做類似的事情的任何想法?

在此先感謝!

編輯:我知道如何下載文件一旦它通過使用下面的代碼拉鍊:

header('Content-Type: application/zip'); 
header('Content-disposition: attachment; filename=filename.zip'); 
header('Content-Length: ' . filesize($zipfilename)); 
readfile($zipname); 
+0

看看內置的[** ** ZipArchive(http://php.net/zip)類。 – mellamokb 2012-07-10 19:33:39

回答

2

感謝@maxhud的幫助,我能夠想出完整的解決方案。這裏是用來實現我想要的結果最終的代碼片段:

<?php 
/* creates a compressed zip file */ 
function create_zip($files = array(),$destination = '',$overwrite = true) { 
    //if the zip file already exists and overwrite is false, return false 
    if(file_exists($destination) && !$overwrite) { return false; } 
    //vars 
    $valid_files = array(); 
    //if files were passed in... 
    if(is_array($files)) { 
    //cycle through each file 
    foreach($files as $file) { 
     //make sure the file exists 
     if(file_exists($file)) { 
     $valid_files[] = $file; 
     } 
    } 
    } 
    //if we have good files... 
    if(count($valid_files)) { 
    //create the archive 
    $zip = new ZipArchive(); 
    if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { 
     return false; 
    } 
    //add the files 
    foreach($valid_files as $file) { 
     $zip->addFile($file,$file); 
    } 
    //debug 
    //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status; 

    //close the zip -- done! 
    $zip->close(); 

    //check to make sure the file exists 
    return file_exists($destination); 
    } 
    else 
    { 
    return false; 
    } 
} 



$files_to_zip = array(
    'upload/1_3266_671641323389_14800358_42187034_1524052_n.jpg', 'upload/1_3266_671641328379_14800358_42187035_3071342_n.jpg' 
); 
//if true, good; if false, zip creation failed 
$zip_name = 'my-archive.zip'; 
$result = create_zip($files_to_zip,$zip_name); 

if($result){ 
header('Content-Type: application/zip'); 
header('Content-disposition: attachment; filename=filename.zip'); 
header('Content-Length: ' . filesize($zip_name)); 
readfile($zip_name); 
} 
?> 
1

一個PHP命令,可讓您運行系統命令

和類似

系統命令

通常效率更高。我的

EX創建文件系統的備份和覆蓋以前的備份

$uploads = wp_upload_dir(); 
$file_name = 'backup_filesystem.tar.gz'; 
unlink($uploads['basedir'] . '/' . $file_name); 

ob_start(); 
$output = shell_exec(sprintf('tar -zcvf %s/%s %s', $uploads['basedir'], $file_name, ABSPATH)); 
ob_end_clean(); 

注:如果輸出緩衝你的php到shell命令有輸出,你不想已經發出錯誤

一個頭
+0

關於爲什麼這個投票被批准的任何建設性的批評? – 2012-07-10 20:06:16

+0

我不確定,我認爲這是一個很好的建議。我不是那個投下你答案的人。 – user1048676 2012-07-10 20:15:49

+0

仇恨者會討厭 – 2012-07-10 22:02:39

相關問題