以下使用編譯方式安裝 zip extension:
到 http://pecl.php.net/package/zip 下載 PECL 的 zip extension
wget http://pecl.php.net/get/zip-1.12.5.tgz解壓縮編譯安裝
tar zxvf zip-1.12.5.tgz cd zip-1.12.5 /usr/local/php/bin/phpize #若無法自動找到php-config,則須使用--with-php-config指定php-config的位置 ./configure --with-php-config=/usr/local/php/bin/php-config make make install修改 php.ini 加入 zip 的 extension
extension = zip.so之後再依 PHP 執行模式,重新啟動 php 或 apache、nginx 後即可。
ZipArchive 產生壓縮檔案範例(產生一個文字檔,壓縮後下載)
$str = "test...test..."; //檔案內容
$filename = "testfile"; //檔案名稱
$filename_txt = $filename . ".txt";
$filename_zip = $filename . ".zip";
$dir = "/home/backup"; //暫存檔目錄
$pwd_txt = $dir . "/" . $filename_txt;
$pwd_zip = $dir . "/" . $filename_zip;
$res_file = file_put_contents($pwd_txt, $str);
unset($str);
if(FALSE === $res_file){
die("產生檔案失敗");
}else{
$zip = new ZipArchive;
$res_zip = $zip->open($pwd_zip, ZipArchive::CREATE);
if (TRUE === $res_zip) {
$zip->addFile($pwd_txt, $filename_txt);
$zip->close();
unlink($pwd_txt);
}else{
unlink($pwd_txt);
die("產生壓縮檔失敗");
}
}
if (file_exists($pwd_zip)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($pwd_zip));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($pwd_zip));
readfile($pwd_zip);
exit;
}
參考:
http://php.net/manual/en/zip.installation.php
http://php.net/manual/en/install.pecl.phpize.php
http://php.net/manual/en/function.readfile.php
沒有留言:
張貼留言