PHP Realizes Packaging zip and Downloading

  • 2021-10-16 01:17:29
  • OfStack

The specific code is as follows:


$file_template = FCPATH.'canddata/cand_picture.zip';// Before that, you must create a new one in your project directory 1 Empty zip Package (must exist) 
$downname = $card.'.zip';// What you're about to pack zip File name 
$file_name = FCPATH.'canddata/'.$card.'.zip';// After packing you up zip The directory in which it is stored 
$result = copy( $file_template, $file_name );// The original project directory exists zip Duplicate 1 A new one to another 1 Directories (can be renamed in the original directory) 
$zip = new ZipArchive();// New 1 Objects 
if ($zip->open($file_name, ZipArchive::CREATE) === TRUE) { // Open the empty one after you copied it zip Bag 
    $zip->addEmptyDir($card);// In zip Compressed package construction 1 Empty folders, returned on success  TRUE ,   Or return on failure  FALSE
    // The following is my scene business processing, which can be processed according to my own scene needs (mine is to package all the pictures) 
    $i = 1;
    foreach ($cand_photo as $key3 => $value3) {
          $file_ext = explode('.',$value3['cand_face']);// Get the suffix name of the picture 
          $zip->addFromString($card.'/'.$card.'_'.$i.'.'.$file_ext[3] , file_get_contents($value3['cand_face']));// Rename the picture, get the 2 Binary flow) 
          $i++;
    }
    $zip->close();
    $fp=fopen($file_name,"r"); 
    $file_size=filesize($file_name);// Get the bytes of the file 
    // Headers needed to download files  
    Header("Content-type: application/octet-stream"); 
    Header("Accept-Ranges: bytes"); 
    Header("Accept-Length:".$file_size);
    Header("Content-Disposition: attachment; filename=$downname"); 
    $buffer=1024; // Settings 1 Number of bytes read per time, per read 1 The data is output (that is, returned to the browser)  
    $file_count=0; // Total number of bytes read  
    // Returning data to the browser   Stop the output if the download is complete, and stop the output if the download is not complete 1 Straight in the output. Judging whether the download is completed according to the byte size of the file 
    while(!feof($fp) && $file_count<$file_size){  
        $file_con=fread($fp,$buffer);  
        $file_count+=$buffer;  
        echo $file_con;  
    } 
    fclose($fp); 
    // Delete the compressed package and temporary folder after downloading  
    if($file_count >= $file_size) { 
          unlink($file_name); 
    }
}

Summarize


Related articles: