LoginSignup
7
10

More than 5 years have passed since last update.

php ZIPファイル作成

Posted at

php ZIPファイル作成

zipファイルを指定ディレクトリに圧縮する。
(圧縮先に同名ファイルがある場合はunlinkをするがエラーは無視)
zipファイルのオープン・圧縮に失敗した場合は例外を投げる。
(error code は http://php.net/manual/ja/ziparchive.open.php の内容)

function zip($files, $zip_path, $mode = 0755) {
    if (file_exists($zip_path))
        @unlink($zip_path);

    $zip = new ZipArchive();
    if ($res = $zip->open($zip_path, ZipArchive::CREATE) !== true) 
        throw new Exception("Zip create error. ZipArchive error code : ".(string)$res);

    foreach ($files as $file) {
        if ($zip->addFile($file, basename($file)) == FALSE) {
            $zip->close();
            @unlink($zip_path);
            throw new Exception("Zip create error. ZipArchive error file : ".(string)$file);
        }
    }
    $zip->close();
    chmod($zip_path, $mode);
}

備考

php7.0以降で書く場合は、引数・戻り値ともに型指定ができるので下記になる。

function zip(array $files, string $zip_path, int $mode = 0755) {}

参考(ZipArchive クラス)
http://php.net/manual/ja/class.ziparchive.php

7
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
10