Zip the folder with Sub folders using PHP - Kvcodes

Congrats, You are Subscribed to Receive Updates.

Zip the folder with Sub folders using PHP

Zip the folder with Sub folders using PHP. You can zip a whole folder using the this article. But if you want to zip the folder with sub folders,


Use this article and create zip with whole folder and sub folders. Lets start with  Zip creation.

zipFile('path/to/the/zip/folder','', true);

And now, we need to use a function for recursive call so create a function here.

function kv_scanfile($source){


Lets start with folder and file scanning.

if (is_dir($source) === true) {                      
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
        foreach ($files as $file)   {
			$file = str_replace('\\', '/', realpath($file));
			if (is_dir($file) === true)   {
				$zip->addEmptyDir(str_replace($source . '/', '', $flag.$file . '/'));
			else if (is_file($file) === true)   {
				$zip->addFromString(str_replace($source . '/', '', $flag.$file), file_get_contents($file));
	else if (is_file($source) === true){
		$zip->addFromString($flag.basename($source), file_get_contents($source));
	else if (is_dir($source) === true){

and if it detects a file, it will be zipped here. and if it found any directory, which will make an directory inside the zip and call the function again and scan the sub folder files. So it will call recursively, until all the folders are scanned.


About Varadharaj V

The founder of Kvcodes, Varadharaj V is an ERP Analyst and a Web developer specializing in WordPress(WP), WP Theme development, WP Plugin development, Frontaccounting(FA), Sales, Purchases, Inventory, Ledgers, Payroll & HRM, CRM, FA Core Customization, OpenCart Theme Development, PHP, HTML, CSS, jQuery, Bootstrap development and content SEO.

Comment Below

Your email address will not be published. Required fields are marked *


Current ye@r *



Subscribe E-mail Updates

Congrats, You are Subscribed to Receive Updates.


Category Posts