To prepare, use phpInfo () to check for zip extensions


      
echo phpinfo();
? >
Copy the code

If the extension is not installed, please refer to the following method:

1, download the corresponding version of expansion pack: windows.php.net/downloads/p… , for example, I am PHP5.6 (Window7_64-bit OS), then download the following:

2, unzip the php_zip. DLL file to phP-5.6.27-nts /ext

Add the following configuration to php.ini:

extension=php_zip.dll

4. Restart the Apache

Thinkphp5.0 backend controller code:

/ * * * *@name=' compress '*/
public function zip() {
	if(request()->isPost()) {
		try {
			// The folder directory
			$dirPath=ROOT_PATH.'/demo/';
			//zip Directory for saving the compressed package
			$zipPath= ROOT_PATH."/public/update/demo.zip";
			// Create a zip instance
			$zip=new \ZipArchive();
			if($zip->open($zipPath, \ZipArchive::CREATE|\ZipArchive::OVERWRITE)=== TRUE) {
				// Call the method, operate on the root directory to be packed, and pass the ZipArchive object to the method
				addFileToZip($zip.$dirPath.$dirPath);
				// Close the processing zip file
				$zip->close(); }}catch (\Exception $e) {
			$this->error('Compression failed, Error:'.$e);
		}
		$this->success('Compression succeeded'); }}/** * Add folder files to zip *@paramZip ZipArchive object *@paramPath Source folder path *@paramNote: It is recommended that the third parameter be the same as the second parameter because the recursion will change the value of the second parameter. Therefore, the third parameter */ must be passed
function addFileToZip($zip.$path.$root){
    $handler=opendir($path); // Open the current folder
    while(($filename=readdir($handler))! = =false) {if($filename! ="." && $filename! ="..") {// Do not operate with names '.' and '.. 'folder or file
            if(is_dir($path."/".$filename)) {// If one of the objects read is a folder, then recursive
                addFileToZip($zip.$path."/".$filename.$root);
            }else{ 
				// Add the file to the zip object. The second argument is the path to the file in the zip
				$pathFilename=$path . "/" . $filename;
                $zip->addFile($pathFilename, str_replace($root.'/'.' '.$pathFilename));
            }
        }
    }
    @closedir($path);
}
Copy the code