code

PHP를 사용하여 여러 파일을 zip 파일로 다운로드

codestyles 2020. 8. 20. 18:47
반응형

PHP를 사용하여 여러 파일을 zip 파일로 다운로드


PHP를 사용하여 여러 파일을 zip 파일로 다운로드하려면 어떻게해야합니까?


당신이 사용할 수있는 ZipArchiveZIP 파일을 생성하는 클래스를 그것은 클라이언트에 스트리밍. 다음과 같은 것 :

$files = array('readme.txt', 'test.html', 'image.gif');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
  $zip->addFile($file);
}
$zip->close();

스트리밍하려면 :

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

두 번째 행은 브라우저가 사용자에게 다운로드 상자를 표시하도록하고 filename.zip이라는 이름을 프롬프트합니다. 세 번째 줄은 선택 사항이지만 특정 (주로 오래된) 브라우저는 콘텐츠 크기를 지정하지 않고 특정 경우에 문제가 있습니다.


다음은 PHP에서 ZIP을 만드는 작업 예제입니다.

$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name,  ZipArchive::CREATE);
foreach ($files as $file) {
  echo $path = "uploadpdf/".$file;
  if(file_exists($path)){
  $zip->addFromString(basename($path),  file_get_contents($path));  
  }
  else{
   echo"file does not exist";
  }
}
$zip->close();

zip 파일을 만든 다음 헤더를 설정하여 파일을 다운로드하고 zip 내용을 읽고 파일을 출력합니다.

http://www.php.net/manual/en/function.ziparchive-addfile.php

http://php.net/manual/en/function.header.php


php zip lib로 할 준비가되었으며 zend zip lib도 사용할 수 있습니다.

<?PHP
// create object
$zip = new ZipArchive();   

// open archive 
if ($zip->open('app-0.09.zip') !== TRUE) {
    die ("Could not open archive");
}

// get number of files in archive
$numFiles = $zip->numFiles;

// iterate over file list
// print details of each file
for ($x=0; $x<$numFiles; $x++) {
    $file = $zip->statIndex($x);
    printf("%s (%d bytes)", $file['name'], $file['size']);
    print "
";    
}

// close archive
$zip->close();
?>

http://devzone.zend.com/985/dynamically-creating-compressed-zip-archives-with-php/

and there is also php pear lib for this http://www.php.net/manual/en/class.ziparchive.php

참고URL : https://stackoverflow.com/questions/1754352/download-multiple-files-as-a-zip-file-using-php

반응형