Zipar directory with PHP
I have a code that compacts file and directory. The problem is that it compresses the files and directories that are in the root, but the subdirectories they are not compressed, for example I have these directories:
Folder/, folder/file.php, folder / other / folder2, file1.php
It only compacts folder / and file1.php ...
It should compress the file.php, other/, Folder 2 /
Code:
<?php
function Show_files($local){
$zip = new ZipArchive();
if($zip->open('compact.zip', ZIPARCHIVE::CREATE) == TRUE){
$open = opendir($local);
while($folder = readdir($open)){
if(is_dir($local.$folder) && $folder != '.' && $folder != '..'){
echo $local.$folder.'<br>';
$zip->addEmptyDir($folder);
Show_files($local.$folder.'/');
}elseif(is_file($local.$folder) && $folder != '.' && $folder != '..'){
$zip->addFile($local.$folder, $folder);
echo $local.$folder.'<br>';
}
}
}
}
$raiz = str_replace("\\", "/", getcwd())."/";
Show_files($raiz);
?>
1 answers
What is happening is that you are rewriting the file because it is a recursive function, so the instance $zip
it is created every time it goes through the recursive function call. To work out create out instance $zip
and pass as function parameter.
Example with function
:
<?php
function Compact($zip, $cwd) {
$open = opendir($cwd);
while($folder = readdir($open))
{
if ($folder != '.' && $folder != '..'){
if (is_dir($cwd.'/'.$folder))
{
$dir = str_replace('./', '',($cwd.'/'.$folder));
$zip->addEmptyDir($dir);
Compactar($zip, $dir);
}
elseif (is_file($cwd.'/'.$folder))
{
$arq = str_replace('./', '',$cwd.'/'.$folder);
$zip->addFile($arq);
}
}
}
}
$zip = new ZipArchive();
if ($zip->open("arquivoFAfa.zip", ZIPARCHIVE::CREATE) === true){
Compact($zip, ".");
}
$zip->close();
Example with class
extending ZipArchive
<?php
class Zipper extends ZipArchive
{
public function Compact($cwd) {
$open = opendir($cwd);
while($folder = readdir($open))
{
if ($folder != '.' && $folder != '..')
{
if (is_dir($cwd.'/'.$folder))
{
$dir = str_replace('./', '',($cwd.'/'.$folder));
$this->addEmptyDir($dir);
$this->Compact($dir);
}
elseif (is_file($cwd.'/'.$folder))
{
$arq = str_replace('./', '',$cwd.'/'.$folder);
$this->addFile($arq);
}
}
}
}
}
$zip = new Zipper();
if ($zip->open("arquivoFAClassAbc.zip", ZIPARCHIVE::CREATE) === true){
$zip->Compact(".");
}
$zip->close();
Tip: use the second option, because you will not have this instance problem, although the first is only to create the instance outside as reported at the beginning of the response.