zip and download files using php

前端 未结 7 878
暗喜
暗喜 2021-02-02 03:41

I am trying to zip and download files from a folder named \"upload\". Zip file is downloading but I couldn\'t open (extract) it. I am getting an error like \"The archive is eith

7条回答
  •  再見小時候
    2021-02-02 04:06

    I have a client "download-all" button for files stored in a parallel directory on a webserver. Having similar issues to the OP, the following code was created after reading many similar posts.

    The server is running php7.4 on Ubuntu 20, don't forget to install your php's version of zip, mine being php7.4-zip. The HTML uses Bootstrap 4.5.2 and font-awesome 5.13.0

    open( $tmp_file, ZipArchive::CREATE ) ){ 
    
            // $i = 0,1 show the dot and double dot directory in linux
            $i=2; 
    
            while( $i < count( $fileNames ) ){ 
    
               // addFile( 'from location', 'name of individual file')
               $zip->addFile( $directory . "/" . $fileNames[ $i ], $fileNames[ $i ] ); 
               $i++;
            }
    
            $zip->close();
        
            // remove special characters from the about-to-be-created zip filename 
            $cleanName = str_replace(array( ".",",","/","\\"," "),'', $_SESSION["folderName"])
            header("Content-disposition: attachment; filename=" . $cleanName . ".zip");
            header('Content-type: application/zip');
    
            // begin the zip download
            readfile( $tmp_file );
    
            // removes the temporary file created in the "../remoteLinuxDirectory/"
            unlink( $tmp_file );
    
        }else{
            // can be removed, but will dump some info incase the $zip->open fails
            var_dump( $tmp_file );
        }
    }
    ?>
    

    An HTML button:

提交回复
热议问题