<?php
// 安全配置
ini_set('display_errors', 0);
error_reporting(E_ALL);
// 1. 文件验证
$allowedExt = 'zip';
$maxSize = 50 * 1024 * 1024; // 50MB
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $_FILES['upload']['tmp_name']);
if ($_FILES['upload']['size'] > $maxSize) {
die('文件过大(最大50MB)');
}
if (!in_array($mimeType, ['application/zip', 'application/x-zip-compressed'])) {
die('非ZIP格式文件');
}
// 2. 生成安全目标目录
$uploadDir = '/var/www/uploads/unzipped/';
$taskId = uniqid('unzip_', true);
$destDir = $uploadDir . $taskId;
if (!is_dir($destDir)) {
mkdir($destDir, 0750, true);
}
// 3. 安全解压
try {
$zip = new ZipArchive;
$res = $zip->open($_FILES['upload']['tmp_name']);
if ($res !== true) {
throw new Exception('ZIP文件损坏(错误码:' . $res . ')');
}
// 路径穿越防护
$destDirReal = realpath($destDir);
for ($i = 0; $i < $zip->numFiles; $i++) {
$stat = $zip->statIndex($i);
$name = $stat['name'];
// 移除路径分隔符开头(防止绝对路径)
$name = ltrim($name, '/');
// 构建并验证完整路径
$fullPath = $destDirReal . DIRECTORY_SEPARATOR . $name;
$realPath = realpath(dirname($fullPath));
if ($realPath === false || strpos($realPath, $destDirReal) !== 0) {
throw new Exception("路径穿越攻击阻止:{$name}");
}
}
// 执行解压
$zip->extractTo($destDir);
$zip->close();
// 4. 后处理:设置权限
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($destDir, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $item) {
if ($item->isDir()) chmod($item->getPathname(), 0750);
else chmod($item->getPathname(), 0640);
}
// 5. 返回结果
echo json_encode([
'success' => true,
'taskId' => $taskId,
'files' => $zip->numFiles,
'dest' => '/unzipped/' . $taskId
]);
} catch (Exception $e) {
error_log("Unzip failed: " . $e->getMessage());
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}