我有以下代码来创建zip存档。如何检查归档文件是否实际创建?
当未添加任何文件时,调用close
仍返回true吗?
$profiles = $profileRepository->getProfiles()->get();
$fileName = time() . '-' . uniqid() . '-' . '.zip';
$filePath = storage_path('app/bulkdownloads/' . $fileName);
$zip = new ZipArchive;
if ($zip->open($filePath, ZipArchive::CREATE) === TRUE) {
foreach($profiles as $profile) {
if (file_exists(storage_path('app/' . $profile->file_path)))
$zip->addFile(storage_path('app/' . $profile->file_path), $profile->name . '-' . $profile->id . '.' . pathinfo($profile->file_path, PATHINFO_EXTENSION));
}
$res = $zip->close();
if ($res == true) {
$newFile = \App\File::create([
"name" => $fileName
"path" => 'bulkdownloads/' . $fileName,
"size" => filesize($filePath),
"mime_type" => mime_content_type($filePath),
]);
}
}
答案 0 :(得分:0)
我只需要按如下方式重构代码即可使其工作:
$profiles = $profileRepository->getProfiles()->get();
$fileName = time() . '-' . uniqid() . '-' . '.zip';
$filePath = storage_path('app/bulkdownloads/' . $fileName);
$zip = new ZipArchive;
if ($zip->open($filePath, ZipArchive::CREATE) === TRUE) {
foreach($profiles as $profile) {
if (file_exists(storage_path('app/' . $profile->file_path)))
$zip->addFile(storage_path('app/' . $profile->file_path), $profile->name . '-' . $profile->id . '.' . pathinfo($profile->file_path, PATHINFO_EXTENSION));
}
$zip->close();
}
if (file_exists($filePath)) {
$newFile = \App\File::create([
"name" => $fileName
"path" => 'bulkdownloads/' . $fileName,
"size" => filesize($filePath),
"mime_type" => mime_content_type($filePath),
]);
}
答案 1 :(得分:0)
如果每个zip操作有效,它将返回一个布尔值,因此您需要检查所有布尔值:
$profiles = $profileRepository->getProfiles()->get();
$fileName = time() . '-' . uniqid() . '-' . '.zip';
$filePath = storage_path('app/bulkdownloads/' . $fileName);
$zip = new ZipArchive;
if ($zip->open($filePath, ZipArchive::CREATE) === TRUE) {
$res = true;
foreach($profiles as $profile) {
if (file_exists(storage_path('app/' . $profile->file_path)))
$res = $res && $zip->addFile(storage_path('app/' . $profile->file_path), $profile->name . '-' . $profile->id . '.' . pathinfo($profile->file_path, PATHINFO_EXTENSION));
else
$res = false;
}
$res = $res && $zip->close();
if ($res == true) {
$newFile = \App\File::create([
"name" => $fileName
"path" => 'bulkdownloads/' . $fileName,
"size" => filesize($filePath),
"mime_type" => mime_content_type($filePath),
]);
}
}