Create Zip File using PHP

Kailash Singh

Create Zip File using PHP

Published May 02,2022 by Kailash Singh

0 Comment     644 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:

 
<?php
$message = '';
if(isset($_POST['file_upload']))
{
	//file should be less than 2MB
    if (($_FILES['file']['size'] > 2097152))
    {      
        $message = 'File too large. File must be less than 2 MB.'; 

    }else{

    	//Uploading file code start
    	$uploadfile=$_FILES["file"]["tmp_name"];
		$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

		if(extension_loaded('zip'))  
	    { 
	    	$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  
		      
		    $zip->close();

	        if(file_exists($zip_name))  
	        {   
				// push to download the zip  
				header('Content-type: application/zip');  
				header('Content-Disposition: attachment; filename="'.$zip_name.'"');  
				readfile($zip_name);  
				// remove zip file is exists in temp path  
				unlink($zip_name);
	        }  
		    
		}
    }
	
}
?>

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


 


Comments ( 0 )


SEARCH POST HERE

Subscribe My YouTube Channel

Join Our Telegram Channel & Support Eachother

CATEGORIES

INTERVIEW QUESTIONS

PROJECT SOURCE CODE






POPULAR POSTS