При веб-разработке часто необходимо сжать папки или каталоги в один файл для различных целей, таких как загрузка файлов, резервное копирование или передача данных. PHP предоставляет класс ZipArchive, который позволяет нам создавать zip-архивы и управлять ими. В этой статье мы рассмотрим различные методы сжатия папок с помощью класса PHP ZipArchive, а также приведем примеры кода.
Метод 1: сжатие папки и ее содержимого
$folderPath = '/path/to/folder/';
$zipFilePath = '/path/to/archive.zip';
$zip = new ZipArchive();
if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($folderPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
if (!$file->isDir()) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($folderPath) + 1);
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
echo 'Folder compressed successfully!';
} else {
echo 'Failed to create zip archive!';
}
Метод 2: сжатие папки с уровнем сжатия
$folderPath = '/path/to/folder/';
$zipFilePath = '/path/to/archive.zip';
$zip = new ZipArchive();
if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($folderPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
if (!$file->isDir()) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($folderPath) + 1);
$zip->addFile($filePath, $relativePath);
}
}
$zip->setCompressionIndex(0, ZipArchive::CM_DEFAULT);
$zip->close();
echo 'Folder compressed with default compression level!';
} else {
echo 'Failed to create zip archive!';
}
Метод 3. Сжатие папки с защитой паролем
$folderPath = '/path/to/folder/';
$zipFilePath = '/path/to/archive.zip';
$zipPassword = 'secretpassword';
$zip = new ZipArchive();
if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($folderPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
if (!$file->isDir()) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($folderPath) + 1);
$zip->addFile($filePath, $relativePath);
}
}
$zip->setPassword($zipPassword);
$zip->close();
echo 'Folder compressed with password protection!';
} else {
echo 'Failed to create zip archive!';
}
Метод 4: сжатие папки без определенных файлов
$folderPath = '/path/to/folder/';
$zipFilePath = '/path/to/archive.zip';
$excludedFiles = ['file1.txt', 'file2.txt'];
$zip = new ZipArchive();
if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($folderPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
if (!$file->isDir() && !in_array($file->getFilename(), $excludedFiles)) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($folderPath) + 1);
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
echo 'Folder compressed excluding specific files!';
} else {
echo 'Failed to create zip archive!';
}
В этой статье мы рассмотрели различные методы сжатия папок с помощью класса PHP ZipArchive. Мы рассмотрели сжатие папки и ее содержимого, сжатие с определенным уровнем сжатия, добавление защиты паролем в архив и исключение определенных файлов из сжатия. Эти методы обеспечивают гибкость и контроль при сжатии папок в PHP.
Не забывайте правильно обрабатывать ошибки и проверки в своем коде, чтобы обеспечить плавное выполнение. Сжатие папок с помощью класса PHP ZipArchive открывает различные возможности для управления файлами и передачи данных в проектах веб-разработки.