這是我用來解壓縮檔案的函式。
它包含下列選項
* 解壓縮到您喜歡的任何目錄
* 解壓縮到 zip 檔案的目錄
* 解壓縮到與 zip 檔案名稱相同的目錄(位於 zip 檔案的目錄中)。(例如:C:\test.zip 將解壓縮到 C:\test\)
* 是否覆寫現有檔案
* 它會使用函式 Create_dirs($path) 建立不存在的目錄
您應該使用帶有斜線 (/) 的絕對路徑,而不是反斜線 (\)。
我使用 PHP 5.2.0 和載入的 php_zip.dll 擴充功能測試過。
<?php
function unzip($src_file, $dest_dir=false, $create_zip_name_dir=true, $overwrite=true)
{
if ($zip = zip_open($src_file))
{
if ($zip)
{
$splitter = ($create_zip_name_dir === true) ? "." : "/";
if ($dest_dir === false) $dest_dir = substr($src_file, 0, strrpos($src_file, $splitter))."/";
create_dirs($dest_dir);
while ($zip_entry = zip_read($zip))
{
$pos_last_slash = strrpos(zip_entry_name($zip_entry), "/");
if ($pos_last_slash !== false)
{
create_dirs($dest_dir.substr(zip_entry_name($zip_entry), 0, $pos_last_slash+1));
}
if (zip_entry_open($zip,$zip_entry,"r"))
{
$file_name = $dest_dir.zip_entry_name($zip_entry);
if ($overwrite === true || $overwrite === false && !is_file($file_name))
{
$fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
file_put_contents($file_name, $fstream );
chmod($file_name, 0777);
echo "save: ".$file_name."<br />";
}
zip_entry_close($zip_entry);
}
}
zip_close($zip);
}
}
else
{
return false;
}
return true;
}
function create_dirs($path)
{
if (!is_dir($path))
{
$directory_path = "";
$directories = explode("/",$path);
array_pop($directories);
foreach($directories as $directory)
{
$directory_path .= $directory."/";
if (!is_dir($directory_path))
{
mkdir($directory_path);
chmod($directory_path, 0777);
}
}
}
}
unzip("C:/zipfiletest/zip-file.zip", false, true, true);
unzip("C:/zipfiletest/zip-file.zip", "C:/another_map/zipfiletest/", true, false);
?>