67448

Question:
I'm trying to retrieve folders 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;
}
}
}
Problem that if the zip folder contain other files which is not included inside the folders it return all the files names. I need it to return folders names only and discard any files name.
Answer1:You can try to check when $info['crc']
equals to 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;
}
}
<strong>Usage example:</strong>
$z = new zipadmin('test.zip', './'); // test.zip in my example is in same folder
print_r($z->listzip());
<strong>Output</strong> (array of root-directories only):
Array
(
[0] => folder1
[1] => folder2
[2] => folder3
[3] => folder4
)
In my test.zip
archive I have few files in root directory of archive and 4 directories folder1
, folder2
, folder3
and folder4
with some files and sub-directories inside them. Running method against archive with no folders returns boolean <strong>false</strong>.
<strong>Update:</strong>
<ul><li>Fixed regex pattern to match everything before first slash/
.</li>
</ul>