PHP如何打包下載ziparchive的使用

黑燈舞 9年前發布 | 21K 次閱讀 PHP PHP開發

之前在做一個有關文件操作的時候,遇到一個多文件下載的問題

//php 打包
/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
    //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 php 系統自帶類,具體使用方法參照:http://cn2.php.net/manual/en/class.ziparchive.php
        $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;
    }
}
//Sample Usage
$files_to_zip = array(
    'preload-images/1.jpg',
    'preload-images/2.jpg',
    'preload-images/5.jpg',
    'kwicks/ringo.gif',
    'rod.jpg',
    'reddit.gif'
);

//if true, good; if false, zip creation failed
$result = create_zip($files_to_zip,'my-archive.zip');
// php下載
    function download($file_dir='web/uploadfile/', $file_name)
    {
        //檢查文件是否存在  
        if (! file_exists ( $file_dir . $file_name )) {  
            echo "文件找不到";  
            exit ();  
        } else {  
            //打開文件  
            $file = fopen ( $file_dir . $file_name, "r" );  
            //輸入文件標簽   
            Header ( "Content-type: application/octet-stream" );  
            Header ( "Accept-Ranges: bytes" );  
            Header ( "Accept-Length: " . filesize ( $file_dir . $file_name ) );  
            Header ( "Content-Disposition: attachment; filename=" . $file_name );  
            //輸出文件內容   
            //讀取文件內容并直接輸出到瀏覽器  
            echo fread ( $file, filesize ( $file_dir . $file_name ) );  
            fclose ( $file );  
            exit ();  
        } 
    }

轉自:php 如何打包下載ziparchive的使用

 本文由用戶 黑燈舞 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!