Last active
February 14, 2017 12:39
-
-
Save wolfthemes/cf453d37d85c8e76b9a4a80f99f93d3d to your computer and use it in GitHub Desktop.
Zip a folder and all subfolders in it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Zip a folder | |
| * | |
| * @param string $src path to folder path/folder | |
| * @param string $dest destination name path/folder.zip | |
| * @see http://stackoverflow.com/questions/4914750/how-to-zip-a-whole-folder-using-php | |
| */ | |
| function zipit( $src, $dest = null ) { | |
| // Get real path for our folder | |
| $path = realpath( $src ); | |
| if ( ! $dest ) { | |
| $dest = $src . '.zip'; | |
| } | |
| // Initialize archive object | |
| $zip = new ZipArchive(); | |
| $zip->open( $dest, ZipArchive::CREATE | ZipArchive::OVERWRITE); | |
| // Create recursive directory iterator | |
| /** @var SplFileInfo[] $files */ | |
| $files = new RecursiveIteratorIterator( | |
| new RecursiveDirectoryIterator( $path ), | |
| RecursiveIteratorIterator::LEAVES_ONLY | |
| ); | |
| foreach ( $files as $name => $file ) { | |
| // Skip directories (they would be added automatically) | |
| if ( ! $file->isDir() ) { | |
| // Get real and relative path for current file | |
| $file_path = $file->getRealPath(); | |
| $relative_path = substr( $file_path, strlen( $path ) + 1); | |
| // Add current file to archive | |
| $zip->addFile( $file_path, $relative_path ); | |
| } | |
| } | |
| // Zip archive will be created only after closing object | |
| $zip->close(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment