此教學為直接產生文件檔再壓縮後直接下載。

一、用法介紹:

1. file_put_contents(文件位置, 訊息):將數據寫入文件 

例:file_put_contents("/", "你好嗎?!")

2. unset():銷毀指定的變量。

3. die():此語言構造等效於exit()

4. open(pwd_zip, ZipArchive::CREATE):開啟壓縮檔,ZipArchive::CREATE 為如果存檔不存在,請創建它。

5. addFile(檔案位置加名稱, 檔案名稱):從給定路徑將文件添加到ZIP存檔中。

6. unlink(檔案位置加名稱):刪除文件

7. file_exists():函数检查文件或目录是否存在。

8. header('Content-Disposition: attachment; filename=檔案名稱'):內容描述:檔名

9. readfile(檔案位置):執行完下載

二、程式範例:

<?php
if (!extension_loaded('zip')) {
    if (!dl('zip.so')) {
        exit;
    }
}
str = "文件檔案內容!!!!"; 
file = "test"; 
file_txt = file . ".txt";
file_zip = file . ".zip";
p_txt = "/" . file_txt;
p_zip = "/" . file_zip;
res_file = file_put_contents(p_txt, str);
unset(str);
if(FALSE == res_file){
    die("產生檔案失敗!!");
}else{
    zip = new ZipArchive;
    res_zip = zip->open(p_zip, ZipArchive::CREATE);
    if (TRUE == res_zip) {
        zip->addFile(p_txt, file_txt);
        zip->close();
        unlink(p_txt);
    }else{
        unlink(p_txt);
        die("產生壓縮檔失敗!!");
    }
}

if (file_exists(p_zip)) { 
    header('Content-Disposition: attachment; filename='.basename(p_zip));
    readfile(p_zip);
    exit;
}


?>

文章標籤
全站熱搜
創作者介紹
創作者 小甲學習地 的頭像
小甲學習地

學習資訊部落

小甲學習地 發表在 痞客邦 留言(0) 人氣(84)