Jump to content

Help with recursive function


ProfHawking

Recommended Posts

Hi Everyone,

I am having a nightmare with a function to zip up a directory.

 

I think i know what the issue is but i don't know how to fix it.

The zip file is created, then the function is supposed to add folders & files, but it cannot reference the zip functions as they are outside of the function.

 

I get the error:

Fatal error: Call to a member function addEmptyDir() on a non-object

When it is run.

 

 

This is the code i'm using:

 


<?php

// begin zip handles =======================
// begin new zip
$zip = new ZipArchive();
// set temp filename
$filename = "newzip.zip";
// create zip file with name $filename
if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
   exit("cannot open <$filename>\n");
}
// end zip handles =======================

// loop through specified directory and add files to zip
zipDirectory("somedir");

// begin finish zip file ====================
// echo the number of files in the zip
echo "numfiles: " . $zip->numFiles . "\n";
// close the zip file
$zip->close();
// end zip file ============================



// zipdir function
function zipDirectory( $path, $level = 0 ){
// begin folder handles =======================
// ignore folder navs and thumbnail directories
$ignore = array( 'cgi-bin', '.', '..', 'mcith' );
// Open the directory to the handle $dh
$dh = @opendir( $path );
    // Loop through the directory
    while( false !== ( $file = readdir( $dh ) ) ){
	// Check that this file is not to be ignored
        if( !in_array( $file, $ignore ) ){
            if( is_dir( "$path/$file" ) ){
            // Its a directory, so we need to keep reading down...
			// add directory to zip
			$zip->addEmptyDir($path."/".$file);
                echo "<strong>$path/$file</strong><br />";
			// continue recursively looping through this folder
                zipDirectory( "$path/$file", ($level+1) );
            } else {
			// found a file, add it to the zip
			$zip->addFile($path."/".$file);
                echo "$path/$file<br />";
            }
        }
    }
    // Close the directory handle
    closedir( $dh );
// end folder handles =======================
} // end function

?>


 

The errors come up because of these two lines in the function:

$zip->addEmptyDir($path."/".$file);

and

$zip->addFile($path."/".$file);

 

 

 

Does anyone know how i can overcome this or perhaps do it in a different way?

 

Many thanks indeed!!

 

Link to comment
https://forums.phpfreaks.com/topic/151220-help-with-recursive-function/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.