сжать / архивировать папку с помощью php-скрипта

Есть ли способ сжать / архивировать папку на сервере с помощью php-скрипта в .zip или .rar или в любой другой сжатый формат, чтобы по запросу мы могли архивировать папку, а затем дать ссылку для скачивания

заранее спасибо

Вот пример:

<?php // Adding files to a .zip file, no zip file exists it creates a new ZIP file // increase script timeout value ini_set('max_execution_time', 5000); // create object $zip = new ZipArchive(); // open archive if ($zip->open('my-archive.zip', ZIPARCHIVE::CREATE) !== TRUE) { die ("Could not open archive"); } // initialize an iterator // pass it the directory to be processed $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("themes/")); // iterate over the directory // add each file found to the archive foreach ($iterator as $key=>$value) { $zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key"); } // close and save archive $zip->close(); echo "Archive created successfully."; ?> 

Остерегайтесь возможной проблемы в примере Аднана: если целевой файл myarchive.zip находится внутри исходной папки, вам нужно исключить его в цикле или запустить итератор перед созданием архивного файла (если он еще не существует ). Вот отредактированный скрипт, который использует последний вариант, и добавляет некоторые конфигурационные vars вверху. Это нельзя использовать для добавления в существующий архив.

 <?php // Config Vars $sourcefolder = "./" ; // Default: "./" $zipfilename = "myarchive.zip"; // Default: "myarchive.zip" $timeout = 5000 ; // Default: 5000 // instantate an iterator (before creating the zip archive, just // in case the zip file is created inside the source folder) // and traverse the directory to get the file list. $dirlist = new RecursiveDirectoryIterator($sourcefolder); $filelist = new RecursiveIteratorIterator($dirlist); // set script timeout value ini_set('max_execution_time', $timeout); // instantate object $zip = new ZipArchive(); // create and open the archive if ($zip->open("$zipfilename", ZipArchive::CREATE) !== TRUE) { die ("Could not open archive"); } // add each file in the file list to the archive foreach ($filelist as $key=>$value) { $zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key"); } // close the archive $zip->close(); echo "Archive ". $zipfilename . " created successfully."; // And provide download link ?> <a href="http:<?php echo $zipfilename;?>" target="_blank"> Download <?php echo $zipfilename?></a> 

PHP поставляется с расширением ZipArchive , которое подходит именно вам.