Create Zip File using PHP

Kailash Singh

Create Zip File using PHP

Published May 02,2022 by Kailash Singh

0 Comment     1570 Views    

In this tutorial, we are going to teach you, how to create zip file using php. The ZIP is a commonly used file format to archive files with data compression.

When you want to allow the user to download folders and files at once from the server, you need to create a ZIP file on the fly. It helps to compress files and create an archive to download files at once. The ZIP file can be created dynamically using PHP, and the archive file can be saved on the server from the PHP script easily.


ZipArchive Library:

ZipArchive method in PHP is used to add the file, new directory, and able to read the zip in PHP. ZipArchive is a class rather than a method; ziparchive contains multiple methods; by the use of it, we can perform various operations on the zip in PHP.


Create Folder, where your file will be slaved


Source Code:

$message = '';
	//file should be less than 2MB
    if (($_FILES['file']['size'] > 2097152))
        $message = 'File too large. File must be less than 2 MB.'; 


    	//Uploading file code start
		$image_upload = $_FILES['file']['name'];
		$image_upload1 = @end(explode('.', $image_upload));
		$image_upload2 = strtolower($image_upload1);
		$new_image_upload = time().'.'.$image_upload2;
		$image_upload_path = './files/'.$new_image_upload;				
		move_uploaded_file($_FILES['file']['tmp_name'], $image_upload_path);
		//Uploading file code end

	    	$folder = "files/";	
			$zip = new ZipArchive(); // Load zip library   

			$zip_name = time().".zip"; // Zip name  

			if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)  
			 	// Opening zip file to load files  
				$error .= "* Sorry ZIP creation failed at this time";  
			$zip->addFile($folder.$new_image_upload); // Adding files into zip  

				// push to download the zip  
				header('Content-type: application/zip');  
				header('Content-Disposition: attachment; filename="'.$zip_name.'"');  
				// remove zip file is exists in temp path  

		<form method="post" action="" enctype="multipart/form-data">
			<input type="file" name='file' required >
			<button type="submit" name="file_upload">Create</button>
		<p style="color: red;"><?php echo $message; ?></p>


Comments ( 0 )