Get folder names only from zip file with php?
I am trying to get the folder name from a zip file. I wrote this simple function:
<?php
class zipadmin{
private $filename ;
private $folder ;
public function __construct($filename,$folder){
$this->zip = new ZipArchive;
$this->file = $filename ;
$this->folder = $folder ;
}
public function listzip(){
if ($this->zip->open($this->file) == TRUE) {
$info = $this->zip->statIndex(0);
$output = str_replace('/','',$info['name']);
return $output;
}
}
}
The problem is, if the zip folder contains other files that are not included in the folders, it returns all the filenames. I need them to return only folder names and discard file names.
source to share
You can check when $info['crc']
is zero.
class zipadmin{
private $file;
private $folder;
private $zip;
public function __construct($filename, $folder) {
$this->zip = new ZipArchive;
$this->file = $filename ;
$this->folder = $folder ;
}
public function listzip() {
$res = false;
if ($this->zip->open($this->folder . $this->file) == TRUE) {
$i = 0;
while ($info = $this->zip->statIndex($i)) {
if ($info['crc'] == 0 && preg_match('#^[^/]*?/$#', $info['name']))
$res[] = preg_replace('#^([^/]*?)/$#', '$1', $info['name']);
$i++;
}
}
return $res;
}
}
Usage example:
$z = new zipadmin('test.zip', './'); // test.zip in my example is in same folder
print_r($z->listzip());
Output (array only for root directories only):
Array
(
[0] => folder1
[1] => folder2
[2] => folder3
[3] => folder4
)
In my archive test.zip
I have some files in the root directory of the file and directory 4 folder1
, folder2
, folder3
and folder4
with some files and subdirectories within them. Running the method against an archive with no folders returns boolean false .
Update:
- Fixed regex pattern to match all before slash first
/
.
source to share