LoginSignup
13
12

More than 5 years have passed since last update.

php ZIPファイル解凍

Last updated at Posted at 2017-01-11

php ZIPファイル解凍

zipファイルを指定ディレクトリに解凍して、中のファイル名の配列を返す。
zipファイルのオープン・解凍に失敗した場合はfalseを返却。
(解凍先に同名ファイルがある場合はunlinkをするがエラーは無視)

public function unzip($zip_path, $unzip_dir, $file_mod = 0755) {
    $zip = new ZipArchive();
    if ($zip->open($zip_path) !== TRUE) 
        return FALSE;

    $unzip_dir = (substr($unzip_dir, -1) == '/') ? $unzip_dir : $unzip_dir.'/';
    for ($i = 0; $i < $zip->numFiles; $i++) 
        if(file_exists($unzip_dir.$zip->getNameIndex($i))
            @unlink($unzip_dir.$zip->getNameIndex($i))

    if ($zip->extractTo($unzip_dir) !== TRUE) {
        $zip->close();
        return FALSE;
    }

    $files = [];
    for ($i = 0; $i < $zip->numFiles; $i++) {
        $files[] = $zip->getNameIndex($i);
        if(file_exists($unzip_dir.$zip->getNameIndex($i))
            chmod($unzip_dir.$zip->getNameIndex($i), $file_mod)
    }
    $zip->close();
    return $files;
}

備考

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

public function unzip(string $zip_path, string $unzip_dir, int $file_mod = 0755) {}

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

13
12
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
13
12