Last active
April 23, 2024 13:01
-
-
Save Immolare/03b5fabcf921b938ba321f402490990c to your computer and use it in GitHub Desktop.
Merge files from zip archive to a destination folder
This file contains 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
const ZIP_FILEPATH = '/path'; | |
const ZIP_FILENAME = 'archive.zip'; | |
const ZIP_SUBDIRNAME = 'subdir'; // Folder inside archive | |
const ZIP_MAINDIRNAME = "maindir"; // Target folder containing files | |
/* If small archive folder use PHP. Note, on some big archives it doesn't extract all subfolders and files */ | |
function mergeFromZipPHP() | |
{ | |
$zip = new ZipArchive; // need to be isntalled on server | |
$zipPath = self::ZIP_FILEPATH.'/'.self::ZIP_FILENAME; | |
$zipExtractPath = self::ZIP_FILEPATH.'/'; | |
try { | |
if (($error = $zip->open($zipPath)) !== TRUE) { | |
throw new Exception($error); | |
} | |
$zip->extractTo($zipExtractPath); | |
$zip->close(); | |
/* Bash cmd to merge files together in the dest directory : copy non present files / override / keep structure */ | |
shell_exec("cp -RT $zipExtractPath/".self::ZIP_SUBDIRNAME.'/'.self::ZIP_MAINDIRNAME."/ ".self::ZIP_FILEPATH."/"); | |
/* Remove current extracted directory and zip as you don't need them anymore */ | |
shell_exec("rm -rf $zipExtractPath/".self::ZIP_SUBDIRNAME); | |
shell_exec("rm -f $zipPath"); | |
} catch(Exception $e) { | |
return $e->getMessage() === ZipArchive::ER_NOENT ? false : $e->getMessage(); | |
} | |
return true; // return what you want | |
} | |
/* Else use bash cmd to be faster */ | |
function mergeFromZipBash() | |
{ | |
$zipPath = self::ZIP_FILEPATH.'/'.self::ZIP_FILENAME; | |
$zipExtractPath = self::ZIP_FILEPATH.'/'; | |
shell_exec("unzip -o $zipPath -x -d $zipExtractPath"); | |
/* Bash cmd to merge files together in the dest directory : copy non present files / override / keep structure */ | |
shell_exec("cp -RT $zipExtractPath/".self::ZIP_SUBDIRNAME.'/'.self::ZIP_MAINDIRNAME."/ ".self::ZIP_FILEPATH."/"); | |
/* Remove current extracted directory and zip as you don't need them anymore */ | |
shell_exec("rm -rf $zipExtractPath/".self::ZIP_SUBDIRNAME); | |
shell_exec("rm -f $zipPath"); | |
return true; // return what you want | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment