Web 應用常需支援用戶上傳 ZIP 壓縮包並自動解壓到服務器。本文提供基於 PHP ZipArchive 類(現代標準)與舊版 exec() 調用系統命令兩種方案,並包含上傳表單、安全驗證、目錄遍歷防護等完整代碼。
<?php
// upload.php - 上傳表單
?>
<form action="unzip.php" method="post" enctype="multipart/form-data">
<input type="file" name="zipfile" accept=".zip" required>
<button type="submit">上傳並解壓</button>
</form>
<?php
// unzip.php - 處理邏輯
header('Content-Type: text/html; charset=utf-8');
$targetDir = __DIR__ . '/uploads/';
$maxSize = 50 * 1024 * 1024; // 50MB
if (!isset($_FILES['zipfile']) || $_FILES['zipfile']['error'] !== UPLOAD_ERR_OK) {
die('上傳失敗:' . ($_FILES['zipfile']['error'] ?? '未知錯誤'));
}
$file = $_FILES['zipfile'];
if ($file['size'] > $maxSize) die('文件過大,限制 50MB');
// 驗證是否真實 ZIP(MIME + 擴展名 + 文件頭)
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
$allowedMimes = ['application/zip', 'application/x-zip-compressed', 'application/octet-stream'];
if (!in_array($mime, $allowedMimes)) die('非法文件類型:' . $mime);
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ($ext !== 'zip') die('擴展名必須為 .zip');
// 保存臨時文件
$tempZip = $targetDir . 'temp_' . md5(microtime(true)) . '.zip';
if (!move_uploaded_file($file['tmp_name'], $tempZip)) die('臨時文件保存失敗');
// 解壓
$zip = new ZipArchive();
$res = $zip->open($tempZip);
if ($res !== true) {
unlink($tempZip);
die('ZIP 文件打開失敗,錯誤碼:' . $res);
}
// 安全提取:防止目錄遍歷 (../../etc/passwd)
$extractPath = $targetDir . 'extracted_' . date('YmdHis') . '/';
if (!is_dir($extractPath)) mkdir($extractPath, 0755, true);
for ($i = 0; $i < $zip->numFiles; $i++) {
$stat = $zip->statIndex($i);
$filename = $stat['name'];
// 跳過絕對路徑、包含 .. 的惡意路徑
if (strpos($filename, '..') !== false || $filename[0] === '/') continue;
$dest = $extractPath . $filename;
if (substr($filename, -1) === '/') { // 目錄
if (!is_dir($dest)) mkdir($dest, 0755, true);
} else {
$dir = dirname($dest);
if (!is_dir($dir)) mkdir($dir, 0755, true);
$zip->extractTo($extractPath, [$filename]);
}
}
$zip->close();
// 刪除臨時 ZIP
unlink($tempZip);
echo "解壓成功!文件已提取至:
{$extractPath}";
echo "
返回繼續上傳";
若無 ZipArchive 擴展,可調用系統 unzip 命令(需服務器安裝 unzip):
$zipPath = escapeshellarg($tempZip);
$destPath = escapeshellarg($extractPath);
$cmd = "unzip -o {$zipPath} -d {$destPath} 2>&1";
$output = [];
$returnVar = 0;
exec($cmd, $output, $returnVar);
if ($returnVar !== 0) {
die('解壓失敗:' . implode("\n", $output));
}
注意:exec() 存在命令注入風險,務必使用 escapeshellarg() 轉義參數,並嚴格驗證文件名。
PK\003\004)..、絕對路徑)使用 ZipArchive 是現代 PHP 解壓 ZIP 的標準方式,安全、高效、無外部依賴。結合完善的驗證與防護,可構建穩健的在線解壓功能。