Как создать ZIP-файл с помощью PHP и удалить его после загрузки пользователем?

Мне нужно загрузить изображения с других сайтов на мой сервер. Создайте ZIP-файл с этими изображениями. автоматически запускает загрузку созданного ZIP-файла. после завершения загрузки ZIP-файл и изображения должны быть удалены с моего сервера.

Вместо автоматической загрузки ссылка на скачивание также прекрасна. но другая логика остается такой же.

Ну, вам нужно сначала создать zip-файл, используя класс ZipArchive .

Затем отправьте:

  • Правильные заголовки, указывающие браузеру, должны загрузить что-то в виде zip – see header() – на странице этого руководства есть пример, который должен помочь
  • Содержимое zip-файла, используя readfile()

И, наконец, удалите zip-файл с вашего сервера, используя unlink() .

Примечание. В качестве меры предосторожности может быть разумным, чтобы скрипт PHP выполнялся автоматически (обычно , crontab) , который удалял старые zip-файлы во временном каталоге.

Это на случай, если ваш обычный PHP-скрипт иногда прерывается и не удаляет временный файл.

 <?php Zip('some_directory/','test.zip'); if(file_exists('test.zip')){ //Set Headers: header('Pragma: public'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Last-Modified: ' . gmdate('D, d MYH:i:s', filemtime('test.zip')) . ' GMT'); header('Content-Type: application/force-download'); header('Content-Disposition: inline; filename="test.zip"'); header('Content-Transfer-Encoding: binary'); header('Content-Length: ' . filesize('test.zip')); header('Connection: close'); readfile('test.zip'); exit(); } if(file_exists('test.zip')){ unlink('test.zip'); } function Zip($source, $destination) { if (!extension_loaded('zip') || !file_exists($source)) { return false; } $zip = new ZipArchive(); if (!$zip->open($destination, ZIPARCHIVE::CREATE)) { return false; } $source = str_replace('\\', '/', realpath($source)); if (is_dir($source) === true) { $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); foreach ($files as $file) { $file = str_replace('\\', '/', realpath($file)); if (is_dir($file) === true) { $zip->addEmptyDir(str_replace($source . '/', '', $file . '/')); } else if (is_file($file) === true) { $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file)); } } } else if (is_file($source) === true) { $zip->addFromString(basename($source), file_get_contents($source)); } return $zip->close(); } ?> 

Любая идея, сколько загрузок zip-файлов прерывается и их необходимо продолжить?

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

Как только сервер закроет дескриптор файла, счетчик ссылок файла упадет до нуля, и, наконец, его блоки на диске будут выпущены.

Но вы могли потратить много времени на повторное создание zip-файлов, если многие загрузки будут прерваны. Хорошая дешевая оптимизация, если вы можете сойти с рук.

Вот как я смог это сделать в прошлом. В этом коде предполагается, что вы написали файлы на путь, указанный переменной $path . Возможно, вам придется иметь дело с некоторыми проблемами с разрешениями в конфигурации вашего сервера с использованием exec php

  // write the files you want to zip up file_put_contents($path . "/file", $output); // zip up the contents chdir($path); exec("zip -r {$name} ./"); $filename = "{$name}.zip"; header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.urlencode($filename)); header('Content-Transfer-Encoding: binary'); readfile($filename); 

Включить расширение php_curl; (php.ini). Затем используйте приведенный ниже код для создания zip. создайте класс папки и используйте приведенный ниже код:

 <?php include("class/create_zip.php"); $create_zip = new create_zip(); //$url_path,$url_path2 you can use your directory path $urls = array( '$url_path/file1.pdf', '$url_path2/files/files2.pdf' ); // file paths $file_name = "vin.zip"; // zip file default name $file_folder = rand(1,1000000000); // folder with random name $create_zip->create_zip($urls,$file_folder,$file_name); $create_zip->delete_directory($file_folder); //delete random folder if(file_exists($file_name)){ $temp = file_get_contents($file_name); unlink($file_name); } echo $temp; ?> в <?php include("class/create_zip.php"); $create_zip = new create_zip(); //$url_path,$url_path2 you can use your directory path $urls = array( '$url_path/file1.pdf', '$url_path2/files/files2.pdf' ); // file paths $file_name = "vin.zip"; // zip file default name $file_folder = rand(1,1000000000); // folder with random name $create_zip->create_zip($urls,$file_folder,$file_name); $create_zip->delete_directory($file_folder); //delete random folder if(file_exists($file_name)){ $temp = file_get_contents($file_name); unlink($file_name); } echo $temp; ?> 

создайте класс папки и используйте приведенный ниже код:

 <?php class create_zip{ function create_zip($urls,$file_folder,$file_name){ header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.$file_name); header('Content-Transfer-Encoding: binary'); $mkdir = mkdir($file_folder); $zip = new ZipArchive; $zip->open($file_name, ZipArchive::CREATE); foreach ($urls as $url) { $path=pathinfo($url); $path = $file_folder.'/'.$path['basename']; $zip->addFile($path); $fileopen = fopen($path, 'w'); $init = curl_init($url); curl_setopt($init, CURLOPT_FILE, $fileopen); $data = curl_exec($init); curl_close($init); fclose($fileopen); } $zip->close(); } function delete_directory($dirname) { if (is_dir($dirname)) $dir_handle = opendir($dirname); if (!$dir_handle) return false; while($file = readdir($dir_handle)) { if ($file != "." && $file != "..") { if (!is_dir($dirname."/".$file)) unlink($dirname."/".$file); else delete_directory($dirname.'/'.$file); } } closedir($dir_handle); rmdir($dirname); return true; } } ?> - <?php class create_zip{ function create_zip($urls,$file_folder,$file_name){ header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.$file_name); header('Content-Transfer-Encoding: binary'); $mkdir = mkdir($file_folder); $zip = new ZipArchive; $zip->open($file_name, ZipArchive::CREATE); foreach ($urls as $url) { $path=pathinfo($url); $path = $file_folder.'/'.$path['basename']; $zip->addFile($path); $fileopen = fopen($path, 'w'); $init = curl_init($url); curl_setopt($init, CURLOPT_FILE, $fileopen); $data = curl_exec($init); curl_close($init); fclose($fileopen); } $zip->close(); } function delete_directory($dirname) { if (is_dir($dirname)) $dir_handle = opendir($dirname); if (!$dir_handle) return false; while($file = readdir($dir_handle)) { if ($file != "." && $file != "..") { if (!is_dir($dirname."/".$file)) unlink($dirname."/".$file); else delete_directory($dirname.'/'.$file); } } closedir($dir_handle); rmdir($dirname); return true; } } ?> 

Во-первых, вы загружаете изображения с веб-сайта

то с файлами, которые вы скачали, вы создаете zipfile (большой tute)

наконец, вы отправили этот zip-файл в браузер, используя readfile и headers (см. пример 1)

Другое решение: удалить предыдущие файлы перед созданием нового zip-файла:

  // Delete past zip files script $files = glob('*.zip'); //get all file names in array $currentTime = time(); // get current time foreach($files as $file){ // get file from array $lastModifiedTime = filemtime($file); // get file creation time // get how old is file in hours: $timeDiff = abs($currentTime - $lastModifiedTime)/(60*60); //check if file was modified before 1 hour: if(is_file($file) && $timeDiff > 1) unlink($file); //delete file }